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?

  • escaping is needed only in generated sql, data inserted as it should be – Iłya Bursov Mar 15 '19 at 03:57
  • Thank You very much for your quick response. –  Mar 15 '19 at 03: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. – ArtisticPhoenix Mar 15 '19 at 04:27
  • 1
    Possible duplicate of [How to use mysqli prepared statements in PHP?](https://stackoverflow.com/questions/9629328/how-to-use-mysqli-prepared-statements-in-php) – ArtisticPhoenix Mar 15 '19 at 04:30

0 Answers0