Search code examples
phpmysqlsql-injection

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

Solution

  • 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