Escaping Strings with PDO
In the transition from the deprecated mysql library to PDO, one may wonder about an appropriate replacement for the real_escape_string function.
PDO's Approach to Parameter Binding
PDO provides a better solution for escaping strings, eliminating the need for manual string manipulation. Through its Prepare and Execute methods, PDO prepares a query and binds it to specific parameter values, which are automatically escaped.
Benefits of Prepared Statements
Prepared statements offer several advantages:
Example of Prepared Statement Usage
To escape a single quote using prepared statements in PDO, consider the following example:
<?php $pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password"); $statement = $pdo->prepare("INSERT INTO users (name, email) VALUES (?, ?)"); $statement->execute(array("John Doe", "john.doe@example.com")); ?>
Here, the parameters (John Doe and john.doe@example.com) are automatically escaped and bound to the query, ensuring data integrity and protection against SQL injection.
The above is the detailed content of How Does PDO Replace mysql_real_escape_string for Secure String Handling?. For more information, please follow other related articles on the PHP Chinese website!