note 100501 deleted from function.vsprintf by danbrown

From: Date: Wed, 20 Oct 2010 13:41:22 +0000
Subject: note 100501 deleted from function.vsprintf by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-173308@lists.php.net to get a copy of this message
Note Submitter: marcovtwout at hotmail dot com ---- This is a function I wrote to combine vsprintf and mysql_real_escape_string to return safe queries. <?php /** * Returns safe database query. * Usage: prepareQuery("SELECT * FROM x WHERE y = %d'", $id) // single argument * Usage: prepareQuery("SELECT * FROM x WHERE y = %d AND z = '%s'", array($id, $string)) // multiple arguments * Usage: prepareQuery('SELECT * FROM x WHERE y = %2$d AND z = \'%1$s\'', array($string, $id)); //argument swapping * @see http://www.php.net/manual/en/function.sprintf.php * @see http://www.php.net/manual/en/function.vsprintf.php * @param string $sql String according to sprintf format * @param mixed $values single value or array with values * @return string safe query */ function prepareQuery($sql, $values = null) { // Convert single value to array if ($values != null && !is_array($values)) $values = array($values); if (count($values) > 0) { // Escape and replace values $values = array_map('mysql_real_escape_string', $values); $sql = vsprintf($sql, $values); } return $sql; } ?>

« previous php.notes (#173308) next »