A Comprehensive Guide to Enhancing MySQL Code Security
Introduction
The mysql_ extension, while still commonly used, often introduces vulnerabilities in PHP code due to improper handling of user input and error reporting. This article aims to present a secure and efficient code sample that showcases the correct usage of mysql_ functions.
Code Sample
<?php // Set HTTP headers for character encoding header('Content-type: text/html; charset=utf-8'); // Enable error reporting for development and testing error_reporting(E_ALL | E_STRICT); ini_set('display_errors', 1); // In production, set 'display_errors' to 0 to suppress PHP error messages // Database configuration (modify as needed) $config = [ 'host' => '127.0.0.1', 'user' => 'my_user', 'pass' => 'my_pass', 'db' => 'my_database' ]; // Connect to the database and disable MySQL error output $connection = @mysql_connect($config['host'], $config['user'], $config['pass']); if (!$connection) { trigger_error('Unable to connect to database: ' . mysql_error(), E_USER_ERROR); } // Select the database if (!mysql_select_db($config['db'])) { trigger_error('Unable to select db: ' . mysql_error(), E_USER_ERROR); } // Set character encoding for the connection if (!mysql_set_charset('utf8')) { trigger_error('Unable to set charset for db connection: ' . mysql_error(), E_USER_ERROR); } // Accept and sanitize POST values $id = (int) $_POST['id']; // To prevent SQL injection $name = mysql_real_escape_string($_POST['name']); // Protects against SQL injection // Construct and execute the UPDATE query $result = mysql_query( 'UPDATE tablename SET name = "' . $name . '" WHERE id = "' . $id . '"' ); // Check the result and provide feedback if ($result) { echo htmlentities($name, ENT_COMPAT, 'utf-8') . ' updated.'; } else { trigger_error('Unable to update db: ' . mysql_error(), E_USER_ERROR); } ?>
Secure Coding Practices
This code sample addresses the following coding practices to enhance security:
Conclusion
By following these practices, we can create secure and reliable database queries using the mysql_ extension. While PDO is the recommended approach for new PHP applications, this code sample provides a solid foundation for safely using mysql_ functions when necessary.
The above is the detailed content of How Can I Securely Use the `mysql_` Extension in PHP to Prevent SQL Injection and Enhance Code Safety?. For more information, please follow other related articles on the PHP Chinese website!