Home >Backend Development >PHP Tutorial >How Can I Write Secure and Reliable MySQL Code in PHP?
Avoiding Pitfalls in MySQL Code: A Comprehensive Guide
While the MySQL extension offers functionality for database interactions, its use can be fraught with common pitfalls. This comprehensive guide aims to provide a reference for crafting secure and reliable code using the MySQL extension.
Core Principles
Example Code
Consider this example code that updates a record in a MySQL database, addressing the aforementioned issues:
header('Content-type: text/html; charset=utf-8'); error_reporting(E_ALL | E_STRICT); ini_set('display_errors', 1); // Connect to the database $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); } // Use UTF-8 character set mysql_set_charset('utf8'); // Fetch user-submitted data $id = mysql_real_escape_string($_POST['id']); $name = mysql_real_escape_string($_POST['name']); // Prepare and execute the update query $query = 'UPDATE tablename SET name = "' . $name . '" WHERE id = "' . $id . '"'; $result = mysql_query($query); if ($result) { echo htmlentities($name, ENT_COMPAT, 'utf-8') . ' updated.'; } else { trigger_error('Unable to update db: ' . mysql_error(), E_USER_ERROR); }
Additional Considerations
By adhering to these guidelines and leveraging the provided example, you can effectively mitigate the risks associated with using the MySQL extension, ensuring robust and secure database interactions in your PHP code.
The above is the detailed content of How Can I Write Secure and Reliable MySQL Code in PHP?. For more information, please follow other related articles on the PHP Chinese website!