-3

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?

user6181297
  • 113
  • 2
  • 11
  • 1
    [Google examples of SQL injection](https://www.google.co.uk/search?q=examples+of+sql+injection) – Martin Apr 17 '16 at 12:56
  • [This is also a very interesting article](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) stating that there are relatively easy ways to compromise `mysqli_real_escape_string` – Martin Apr 17 '16 at 12:58

1 Answers1

2

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'";
$result=mysqli_query($con,$sql);
$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.

trincot
  • 317,000
  • 35
  • 244
  • 286
  • When does sql injection occur? I mean for what kind of inputs? – user6181297 Apr 17 '16 at 12:52
  • I added an example which plays tricks with the single quote. – trincot Apr 17 '16 at 13:10
  • From which type of sql injections does mysqli_real_escape_string prevent? – user6181297 Apr 17 '16 at 17:38
  • The goal of *mysqli_real_escape_string* was different: it was to avoid invalid SQL syntax caused by quotes in the string that is inserted. By doing so, it does prevent SQL injection that is based on smart use of quotes, but it does not help when the malicious injection has nothing to do with quotes. See the links that were provided in other comments. – trincot Apr 17 '16 at 17:45