10

Just for clarity, can anyone explain why mysqli_real_escape_string has to read:

$query = mysqli_real_escape_string($conn,"SELECT * FROM tbl");

And not just:

$query = mysqli_real_escape_string("SELECT * FROM tbl");

Thanks for any help!

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Richard Tinkler
  • 1,635
  • 3
  • 21
  • 41

1 Answers1

10

Because of charset encoding.

Without the $conn, mysqli_real_escape_string() won't be able to detect which character encoding the connection is using, and will blindly try to escape common dangerous characters - leaving some potentially dangerous charset hacks to go through.

True (not emulated) prepared statements are even better (or more secure, as you prefer), as they take the character encoding of the column instead of the connection into account.

Alix Axel
  • 151,645
  • 95
  • 393
  • 500
  • 1
    That solves problem with `mysql_real_escape_string()` and directly changed charset in query. http://stackoverflow.com/questions/5288953/is-mysql-real-escape-string-broken – Elon Than Oct 15 '13 at 15:12
  • 1
    Thanks Alix Axel! Can you offer a quick explanation of prepared statements? – Richard Tinkler Oct 15 '13 at 15:48
  • 2
    @RichardTinkler: This comment is too short to tell you everything about them, but they are basically prepared queries that have placeholders for the literal values. The database engine (and not the client API implementation) is responsible for replacing (and escaping) the literal values in the respective placeholders. Start by reading http://www.php.net/manual/en/mysqli.prepare.php. – Alix Axel Oct 15 '13 at 15:53