3

I was looking through the docs and stumbled onto mysql_real_escape_string() and I'm not understanding why it's useful when you can just addslashes(). Can someone show me a scenario as to why it's useful?

I'm also curious why it requires a database connection.... that seems like a lot of overhead.

rook
  • 66,304
  • 38
  • 162
  • 239
Ben
  • 60,438
  • 111
  • 314
  • 488
  • 1
    possible duplicates: http://stackoverflow.com/questions/534742/what-does-mysql-real-escape-string-do-that-addslashes-doesnt , http://stackoverflow.com/questions/91216/what-is-the-difference-between-mysql-real-escape-string-and-addslashes , http://stackoverflow.com/questions/1162491/alternative-to-mysql-real-escape-string-without-connecting-to-db ...and some more. – VolkerK Mar 29 '10 at 20:19
  • 1
    @VolkerK yeah but he got a better answer. – rook Mar 30 '10 at 17:28

2 Answers2

7

There is a great article about this here. And this discussion also points out the pros and cons of each solution.

addslashes() was from the developers of PHP whereas mysql_real_escape_string uses the underlying MySQL C++ API (i.e. from the developers of MySQL). mysql_real_escape_string escapes EOF chars, quotes, backslashes, carriage returns, nulls, and line feeds. There is also the charset aspect.

Gad
  • 41,526
  • 13
  • 54
  • 78
2

Nether mysql_real_escape_string() or addslashes() prevent everything (what about xss or even xsrf?), and most importantly nether of them prevent all SQL Injection.

For instance this code is vulnerable to sql injection:

mysql_query("select * from user where id=".mysql_real_escape_string($_GET[id]));

Exploit:

http://localhost/test.php?id=1 or sleep(50)

patch:

mysql_query("select * from user where id='".mysql_real_escape_string($_GET[id])."'");

Use parametrized queries with either ADODB or PDO, this is the only bullet proof sql injection protection.

rook
  • 66,304
  • 38
  • 162
  • 239