views:

103

answers:

3

How secure is this MySQL statement built in a PHP? Would it be vulnerable to an SQL injection?

$sql = sprintf("INSERT IGNORE INTO my_table VALUES(%d, %d, 1, NOW())", 
                 mysql_escape_string($_SESSION['client']['id']), 
                 mysql_escape_string($_POST['id']));
+1  A: 

No it shouldn't be vulnerable.

Here is a detailed article on how to secure your SQL queries in PHP.

http://www.tech-evangelist.com/2007/11/05/preventing-sql-injection-attack/

Christian Toma
A: 

It looks fine to me.

In fact, is there any need to use mysql_escape_string in this case, since sprintf("%d") can only result in a number?

therefromhere
+3  A: 

Yes because %d only results in a number there is no need to escape the string. Using single quotes would provide a speed improvement too. So a safe and fast way is:

$sql = sprintf('INSERT IGNORE INTO my_table VALUES(%d, %d, 1, NOW())', $_SESSION['client']['id'], $_POST['id']);
Al
Got any recent benchmarks for your claim on single quotes improving speed in this instance?
Salaryman
No benchmarks, but it's more of a common sense thing. Before sending the string to sprintf - with double quotes, the interpreter will try to look for $variables and other escaped sequences. The single quotes, it won't. Though the speed difference is too small to really make a difference.
jimyi