Home >Database >Mysql Tutorial >How to Migrate from `mysql_real_escape_string()` to PDO Prepared Statements?
Replacing mysql_real_escape_string() with PDO
In the transition from mysql_* functions to PDO, it's essential to understand that PDO does not have an exact equivalent of mysql_real_escape_string().
Instead of manually escaping strings, PDO relies on prepared statements to protect against SQL injection. Prepared statements use placeholders (?) for values that are inserted later, preventing malicious characters from being executed as code.
Example:
<code class="php"><?php // Connect to the database $db = new PDO('mysql:host=localhost;dbname=test', 'root', 'password'); // Prepare the statement with placeholder for value $stmt = $db->prepare('SELECT * FROM users WHERE username = ?'); // Bind the value to the placeholder (already sanitized via other means) $stmt->bindParam(1, $username); // Execute the statement without fear of SQL injection $stmt->execute(); // Fetch the results $users = $stmt->fetchAll(PDO::FETCH_ASSOC);</code>
Advantages of using PDO:
Note: While PDO::quote() can be used to escape a string, it's generally not recommended as it does not offer the same level of protection as prepared statements.
By adhering to best practices and using prepared statements in PDO, developers can effectively prevent SQL injection vulnerabilities in their code.
The above is the detailed content of How to Migrate from `mysql_real_escape_string()` to PDO Prepared Statements?. For more information, please follow other related articles on the PHP Chinese website!