$sql = 'DELETE FROM `' . $table . '` WHERE `ID` = ?'; 

or

$sql = sprintf('DELETE FROM `%s` WHERE `ID` = ?', $table);

Is there anything to be considered that makes choosing one over the other more than a matter of preference?

I find the sprintf variant cleaner especially when more parameters get involved.

Bjom

    Bjom wrote:

    Is there anything to be considered that makes choosing one over the other more than a matter of preference?

    Nope; both will produce the same string.

    Bjom wrote:

    I find the sprintf variant cleaner especially when more parameters get involved.

    This is one of the advantages of building SQL queries with sprintf when several variables are involved.

    Outside of prepared statements, you could also use sprintf() to do some data type validation, e.g. using '%d' for $_GET['id'] would automatically protect you from any non-numeric input.

      Thank you for verifying, that's what I thought, just wanted to see whether I had overlooked anything.

      Yes the filtering options that come along with sprintf are quite a bonus 🙂

      Bjom

        Write a Reply...