0

I am using mysqli_real_escape_string() function for prevent SQl Injection.My code

<?php

// open a connection
$dhost = 'localhost';
$duser = 'user';
$dpw = 'pass';
$dname = 'db_name';
$connection = mysqli_connect($dhost, $duser, $dpw, $dname);

// test the connection
if(mysqli_connect_errno()){
    die('Something went wrong with the database<br><br> '
    . mysqli_connect_error() . ':' 
    . mysqli_connect_errno());
}

$query = "Isn't it nice that we don't have to escape ' characters all by ourselves?";

echo $query.'<br>';

$escaped = mysqli_real_escape_string($connection , $query);

echo $escaped.'<br>';

mysqli_query($connection,"INSERT into emp (name) VALUES ('$escaped')");
   mysqli_close($connection);

?>

when I print $escaped variable it gives output like :

Isn\'t it nice that we don\'t have to escape \' characters all by ourselves?

But when I saw the database field I found this :

Isn't it nice that we don't have to escape ' characters all by ourselves?

4
  • escaping is needed only in generated sql, data inserted as it should be Commented Mar 15, 2019 at 3:57
  • Thank You very much for your quick response.
    – user9416697
    Commented Mar 15, 2019 at 3:58
  • I would just use prepared statements, which you also dont have to worry about the ' in. That quote breaking your SQL means you sustainable to SQLInjection. Because that is exactly what that is. I don't think i would ever call concatenating data directly into a Query "correct". If you have a fixed string, you just put that in, this implies it's input. And if it's user input you need to prepare it. Commented Mar 15, 2019 at 4:27
  • 1
    Possible duplicate of How to use mysqli prepared statements in PHP? Commented Mar 15, 2019 at 4:30

0