Search code examples
phpmysqlmysqliprepared-statementmysql-real-escape-string

real escape string and mysqli prepare statement conflict


I'm using real escape string and prepared statement in mysqli in that case Ii face a problem when am giving input single quote it saved in database as

"  \'   "

My code is:

$db = new mysqli('localhost', 'root', '', 'test1');

if($db->connect_errno > 0)
{
    die('Unable to connect to database [' . $db->connect_error . ']');

}
$s="a'a";
$s=$db->real_escape_string($s); 
$sql="insert into table1 values(?,?)";
$id="";
$stmt=$db->prepare($sql);
$stmt->bind_param('ss',$id,$s);
$stmt->execute();
if($stmt->errno)
{
    echo $stmt->error;
}
else
{
    echo "inserted successfully";
}

Inserted value is id=0 and val=a\'a.

So how can I validate my user input?


Solution

  • You don't need to use real escape string if you are using prepared statement. If you are using prepared statement strings are escaped automatically.
    One advice: always use prepared statement instead of trivial method which involves use of real_escape_string