Question

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']));
Was it helpful?

Solution

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']);

OTHER TIPS

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/

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?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top