Home >Backend Development >PHP Tutorial >How to Create a Secure and Error-Free PHP MySQL Code Sample?
Perfect Code Sample Using the MySQL Extension
Problem:
In the quest to create a community learning resource for secure and error-free PHP database queries, this hypothetical problem presents the task of generating a perfect code sample using the MySQL extension. The goal is to tackle common issues such as SQL injection, error reporting, and XSS injection.
Solution:
To address the complexities of handling user inputs and ensuring data integrity, the provided solution prioritizes safety and simplicity.
<?php header('Content-type: text/html; charset=utf-8'); error_reporting(E_ALL | E_STRICT); ini_set('display_errors', 1); $config = array( 'host' => '127.0.0.1', 'user' => 'my_user', 'pass' => 'my_pass', 'db' => 'my_database' ); $connection = @mysql_connect($config['host'], $config['user'], $config['pass']); if (!$connection) { trigger_error('Unable to connect to database: ' . mysql_error(), E_USER_ERROR); } if (!mysql_select_db($config['db'])) { trigger_error('Unable to select db: ' . mysql_error(), E_USER_ERROR); } if (!mysql_set_charset('utf8')) { trigger_error('Unable to set charset for db connection: ' . mysql_error(), E_USER_ERROR); } $result = mysql_query( 'UPDATE tablename SET name = "' . mysql_real_escape_string($_POST['name']) . '" WHERE id = "' . mysql_real_escape_string($_POST['id']) . '"' ); if ($result) { echo htmlentities($_POST['name'], ENT_COMPAT, 'utf-8') . ' updated.'; } else { trigger_error('Unable to update db: ' . mysql_error(), E_USER_ERROR); }
This code sample encapsulates the following key principles:
The above is the detailed content of How to Create a Secure and Error-Free PHP MySQL Code Sample?. For more information, please follow other related articles on the PHP Chinese website!