Home >Backend Development >PHP Tutorial >How to Securely Update a MySQL Database Using the MySQLi Extension in PHP?
Perfect MySQL Extension Code Sample
The goal of this question is to provide a concise and secure PHP code sample using the MySQL extension. The code should avoid common errors associated with the mysql_* functions, including:
Code Sample:
<?php header('Content-type: text/html; charset=utf-8'); error_reporting(E_ALL | E_STRICT); ini_set('display_errors', 1); $config = [ '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); } ?>
Explanation:
Note that this code sample is provided as a reference and should not be considered a complete solution for all PHP applications. It is recommended to use PDO extension for modern MySQL applications, as it provides enhanced security and performance.
The above is the detailed content of How to Securely Update a MySQL Database Using the MySQLi Extension in PHP?. For more information, please follow other related articles on the PHP Chinese website!