-2

I know I have to prevent db injections by using the mysqli_real_escape_string()

but where best should I use it?

When declaring variables? e.g.

$username = mysqli_real_escape_string($link, $_POST['username']);

OR

inside the SELECT / INSERT mysql queries?

OR

somewhere else?

Also, do I have to prevent db injection in md5 password? e.g.

$password = mysqli_real_escape_string($link, md5($_POST['password']));

idmean
  • 13,418
  • 7
  • 47
  • 78
SULTAN
  • 1,059
  • 2
  • 11
  • 24
  • 3
    You are using [an unsuitable hashing algorithm](http://php.net/manual/en/faq.passwords.php) and need to [take better care](https://www.owasp.org/index.php/Password_Storage_Cheat_Sheet) of your users' passwords. – Quentin Mar 18 '14 at 17:28
  • If you need your data somehere else than only in DB queries, don´t escape first in a variable. And Quentin is right, drop MD5. – deviantfan Mar 18 '14 at 17:29
  • @deviantfan yes, I will show username and password in the user control panel after login. – SULTAN Mar 18 '14 at 17:37

2 Answers2

0

If you really want to prevent sql injection, you shouldn't even be thinking about escaping. Escaping, while it helps many times, is still not 100% foolproof. There are still ways around escaping when used in combination with a poorly written query.

What you should be doing is preparing your query and binding parameters. It is easy to do and essentially eliminates sql injection as a problem. Personally, once I got used to it, I found it easier. If you like using mysqli, it supports binding. I personally prefer PDO because I like to name my parameters.

There are much better resources for explaining the pros and cons that me rambling right now over what has been said a thousand times before.

How can I prevent SQL injection in PHP?

Community
  • 1
  • 1
Jonathan Kuhn
  • 14,619
  • 2
  • 28
  • 41
-1

An example of this is here on PHP.net

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

mysqli_query($link, "CREATE TEMPORARY TABLE myCity LIKE City");

$city = "'s Hertogenbosch";

/* this query will fail, cause we didn't escape $city */
if (!mysqli_query($link, "INSERT into myCity (Name) VALUES ('$city')")) {
    printf("Error: %s\n", mysqli_sqlstate($link));
}

$city = mysqli_real_escape_string($link, $city);

/* this query with escaped $city will work */
if (mysqli_query($link, "INSERT into myCity (Name) VALUES ('$city')")) {
    printf("%d Row inserted.\n", mysqli_affected_rows($link));
}

mysqli_close($link);
?>