user6181297 user6181297 - 9 months ago 20
PHP Question

What are the disadvantages if I don't use mysqli_real_escape_string()?

As per my knowledge If I don't use mysqli_real_escape_string() I may get a wrong entry in database. Correct me if I am wrong.

Are there any disadvantages?


Don't use it, but use prepared statements instead. This is the way to avoid SQL injection.

In short, you need to do something to prevent that strings are appended to your SQL which would change its meaning (through smart use of quotes and such). While mysqli_real_escape_string solves a great deal of these issues, it is not bullet proof.

Just one example of SQL injection:

Suppose you have this bad code :

$name = $_POST['name'];
$password = $_POST['password'];
$sql = "SELECT role FROM user 
         WHERE name = '$name' AND password = '$password'";
$row = $result->fetch_assoc();
if ($row['role'] === 1) { 
      // do all kinds of stuff allowed to admin.

... and a hacker fills in the user name / password form as follows

username: admin
password: ' OR name='admin

Then image what your SQL will look like:

SELECT role FROM user 
WHERE name = 'admin' AND password = '' OR name='admin'

Which will return the role of the admin, eventhough the password was not correct.