Richard Stelling
Richard Stelling

Reputation: 25665

How Secure is this MySQL statement in a PHP script?

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

Upvotes: 1

Views: 244

Answers (3)

Al.
Al.

Reputation: 2882

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

Upvotes: 3

John Carter
John Carter

Reputation: 55369

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?

Upvotes: 1

Cristian Toma
Cristian Toma

Reputation: 5809

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/

Upvotes: 1

Related Questions