1

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

3 Answers 3

3

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']);
Sign up to request clarification or add additional context in comments.

2 Comments

Got any recent benchmarks for your claim on single quotes improving speed in this instance?
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.
1

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/

Comments

1

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.