What is the PDO equivalent of function mysql_real_escape_string?

April 16, 2019, at 11:10 AM

I am modifying my code from using mysql_* to PDO. In my code I had mysql_real_escape_string(). What is the equivalent of this in PDO?

Answer 1

Well No, there is none!

Technically there is PDO::quote() but it is rarely ever used and is not the equivalent of mysql_real_escape_string()

That's right! If you are already using PDO the proper way as documented using prepared statements, then it will protect you from MySQL injection.

# Example:

Below is an example of a safe database query using prepared statements (pdo)

  try {
     // first connect to database with the PDO object. 
     $db = new \PDO("mysql:host=localhost;dbname=xx;charset=utf8", "xx", "xx", [
       PDO::ATTR_EMULATE_PREPARES => false, 
 } catch(\PDOException $e){
     // if connection fails, show PDO error. 
   echo "Error connecting to mysql: " . $e->getMessage();

And, now assuming the connection is established, you can execute your query like this.

if($_POST && isset($_POST['color'])){ 
    // preparing a statement
    $stmt = $db->prepare("SELECT id, name, color FROM Cars WHERE color = ?");
    // execute/run the statement. 
    // fetch the result. 
    $cars = $stmt->fetchAll(\PDO::FETCH_ASSOC); 

Now, as you can probably tell, I haven't used anything to escape/sanitize the value of $_POST["color"]. And this code is secure from myql-injection thanks to PDO and the power of prepared statements.

It is worth noting that you should pass a charset=utf8 as attribute, in your DSN as seen above, for security reasons, and always enable PDO to show errors in the form of exceptions.


so errors from you database queries won't reveal sensitive data like your directory structure, database username etc.

Last but not least, there are moments when you should not trust PDO 100%, and will be bound to take some extra measures to prevent sql injection, one of those cases is, if you are using an outdated versions of mysql [ mysql =< 5.3.6 ] as described in this answer

But, using prepared statements as shown above will always be safer, than using any of the functions that start with mysql_

Good reads

PDO Tutorial for MySQL Developers

Answer 2

There is none*! The object of PDO is that you don’t have to escape anything; you just send it as data. For example:

$query = $link->prepare('SELECT * FROM users WHERE username = :name LIMIT 1;');
$query->execute([':name' => $username]); # No need to escape it!

As opposed to:

$safe_username = mysql_real_escape_string($username);
mysql_query("SELECT * FROM users WHERE username = '$safe_username' LIMIT 1;");

* Well, there is one, as Michael Berkowski said! But there are better ways.

Answer 3
$v = '"'.mysql_real_escape_string($v).'"'; 

is the equivalent of $v = $this->db->quote($v); be sure you have a PDO instance in $this->db so you can call the pdo method quote()

Answer 4

There is no need of mysql_real_escape_string in PDO.

PDO itself adjust special character in mysql query ,you only need to pass anonymous parameter and bind it run time.like this Suppose you have user table with attribute name,email and password and you have to insert into this use prepare statement like this you can pass name as => $name="Rajes'h ";

it should execute there is no need of equivalent of mysql_real_escape_string

$stmt="INSERT into user(name,email,password) VALUES(:name,:email,password)";
   $pstmt=$dbh->prepare($stmt);//$dbh database handler for executing mysql query
    //next line of code 

}catch(PDOException $pdo){
     echo $pdo->getMessage();
Answer 5

If to answer the original question, then this is the PDO equivalent for mysql_real_escape_string:

function my_real_escape_string($value, $connection) {
    // this fails on: value="hello'";
    return trim ($connection->quote($value), "'");
    return substr($connection->quote($value), 1, -1);       

btw, the mysqli equivalent is:

function my_real_escape_string($value, $connection) {
    return mysqli_real_escape_string($connection, $value);
How to detect emoji in plain text with PHP Preg_Match? REGULAR [E-XX]

How to detect emoji in plain text with PHP Preg_Match? REGULAR [E-XX]

I want to change the expressions in the form [E-01] - [E-02] - [E-03] - [E-04]

Create/Delete Space seperated folder names

Create/Delete Space seperated folder names

When I try to create a folder whose name is seperated by spaces it only takes the first word and ignores the second oneHow do I solve this? I am writing with php to a dovecot sever

Serverload using own postfix with mail() vs phpmailer with external smtp

Serverload using own postfix with mail() vs phpmailer with external smtp

I got a smaller VPS server at the moment ~20%-30% avg load 3 websitesClients need to send emails for order, registration, invoices and newsletter