Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does sprintf() protect against SQL injection?

I have heard that sprintf() protects against SQL injection. Is it true? If so, how?

Why people are recommending to write query like this:

$sql = sprintf('SELECT * FROM TABLE WHERE COL1 = %s AND COL2 = %s',$col1,$col2);
like image 889
Rukmi Patel Avatar asked Jul 11 '11 06:07

Rukmi Patel


2 Answers

sprintf won't protect you! It only replaces the %s

you must mysql_real_escape_string so:

$sql = sprintf('SELECT * FROM TABLE WHERE COL1 = "%s" AND COL2 = "%s"',
mysql_real_escape_string($col1),
mysql_real_escape_string($col2));

is safer injection

note: I suggest you take a look at PDO, it is what I like to use for DBconections and queries

like image 164
beardhatcode Avatar answered Sep 30 '22 22:09

beardhatcode


That doesn't do any protection. Using sprintf makes for more readable code then dropping in and out of a string to run mysql_real_escape_string over each of the variables … but that example doesn't escape the variables at the end so that advantage is lost.

If you want decent protection, use something that provides bound parameters.

like image 38
Quentin Avatar answered Sep 30 '22 20:09

Quentin