Home >Database >Mysql Tutorial >How to Prevent MySQL Injection with PDO Prepared Statements: Is There a PDO Equivalent to `mysql_real_escape_string()`?
PDO Equivalent of mysql_real_escape_string()
In your code migration from mysql_* to PDO, you are seeking an equivalent for mysql_real_escape_string(). However, it's crucial to note that there is no direct equivalent in PDO.
Technically, PDO::quote() exists, but it's not commonly utilized and is not comparable to mysql_real_escape_string().
Proper MySQL Injection Prevention
When using PDO appropriately with prepared statements, you gain protection against MySQL injection. Prepared statements sanitize your inputs, eliminating the need for functions like mysql_real_escape_string().
Example of a Secure Database Query using Prepared Statements
Here's an example of a secure database query using PDO prepared statements:
$db = new PDO( "mysql:host=localhost;dbname=xxx;charset=utf8", "xxx", "xxx", [ PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ] ); // Prepared statement $stmt = $db->prepare("SELECT id, name, color FROM Cars WHERE color = ?"); // Execute statement $stmt->execute(array($_POST['color'])); // Fetch result $cars = $stmt->fetchAll(PDO::FETCH_ASSOC);
As you can see, we haven't escaped or sanitized $_POST['color'], yet the code remains secure from MySQL injection thanks to PDO and the power of prepared statements.
Additional Notes
Conclusion
Using prepared statements as demonstrated above is always safer than resorting to mysql_* functions. PDO's built-in protection mechanisms provide a more robust and secure approach to preventing MySQL injection.
The above is the detailed content of How to Prevent MySQL Injection with PDO Prepared Statements: Is There a PDO Equivalent to `mysql_real_escape_string()`?. For more information, please follow other related articles on the PHP Chinese website!