php – Where should I place mysql_real_escape_string?

php – Where should I place mysql_real_escape_string?

You should place mysql_real_escape_string() directly into the rubbish bin and migrate to mysqli or PDO and learn to use prepared statements instead.

Ive mentioned this before in A Gentle Introduction to Application Security, but the fundamental problem that makes SQL injection possible is the confusion of data and code.

Prepared statements send your query string (SELECT * FROM foo WHERE column = ?) and your parameters ([foo]) in separate packets to the database server. The parameters never get a chance to touch the query string, thus preventing the condition that makes SQL Injection possible in the first place.

Escaping inputs and building the query string does not have the same guarantee. Its possible to do it safely, of course, but if you make one mistake and an unskilled hacker finds it, your entire database is toast. (Keep in mind, SQL Injection is low-hanging fruit.)

TL;DR – Just use Prepared Statements.

Switch to a better solution other than mysql_ .

That being said, if you have to use the deprecated mysql_, I suggest you use sprintf() for readability and ease of use:

$qemail = sprintf(SELECT email FROM ppl WHERE email=%s,

$qr = mysql_query($qemail);

If you have more than one parameter you can have multiple %s and other tags, see sprintf() documentation:

$str_qr = sprintf(SELECT * FROM table, WHERE val=%s, val2=%s, someIntegerField=%d,

$qr = mysql_query($str_qr);

php – Where should I place mysql_real_escape_string?

Leave a Reply

Your email address will not be published. Required fields are marked *