Posts Tagged ‘sprintf’

PHP:Use “sprintf”

Monday, June 30th, 2008

Example 1.Uncleanly Spliced String.

<?php

$sql = “SELECT col1, col2, col3 FROM people WHERE first_name = ‘” . mysql_real_escape_string($first_name) . “‘ AND last_name = ‘” . mysql_real_escape_string($last_name) . “‘AND foo = ‘” . ($bar = “good” ? “good” : “bad”) . “‘ ORDER BY col1″ ;

?>
I see these types of indecipherable strings –like this SQL statement example– all too frequently. The meaning of this query has been lost due to numerous concatenations and escape functions; which means developers have to invest a significant amount of time to comprehend the code.

In order to avoid this this, I use PHP’s sprintf() function. sprintf() is a function that’s part of a family of functions –referred to as the “printf” family of function– that substitute designated tokens with arguments to the function. For example, let’s look at the code in example 3.2.
Example 2: Cleanly Assembled String With sprintf()

<?php

$sql = ‘SELECT col1, col2, col3 ‘ .
‘FROM people ‘ .
‘WHERE first_name = “%s” ‘ .
‘AND last_name = “%s” ‘ .
‘AND foo = “%s” ‘ .
‘ORDER BY col1 ‘;

$sql = sprintf($sql, mysql_real_escape_string($first_name),
mysql_real_escape_string($last_name),
($bar = “good” ? “good” : “bad”));

?>

This method allows developers to regain a sense of the data that they’re representing. In this particular example the %s token means replace with a string. There a number tokens such as %d (decimal) and %f (floating point).