Format/prepare mySQL query using sprintf

Posted by & filed under Frameworks/CMS, Wordpress.

	function sani_prep(){
		$args = func_get_args();
	    if (count($args) < 2)
	        return false;
	    $query = array_shift($args);
	    $args = array_map('mysql_real_escape_string', $args);
	    array_unshift($args, $query);
	    $query = call_user_func_array('sprintf', $args);
	    return $query;

Thanks to

Also note, you can use vsprintf to supply an array as an argument, and also take a look at the WordPress function $wpdb->prepare():

	function prepare( $query = null ) { // ( $query, *$args )
		if ( is_null( $query ) )

		$args = func_get_args();
		array_shift( $args );
		// If args were passed as an array (as in vsprintf), move them up
		if ( isset( $args[0] ) && is_array($args[0]) )
			$args = $args[0];
		$query = str_replace( "'%s'", '%s', $query ); // in case someone mistakenly already singlequoted it
		$query = str_replace( '"%s"', '%s', $query ); // doublequote unquoting
		$query = preg_replace( '|(?<!%)%s|', "'%s'", $query ); // quote the strings, avoiding escaped strings like %%s
		array_walk( $args, array( &$this, 'escape_by_ref' ) );
		return @vsprintf( $query, $args );

Leave a Reply

  • (will not be published)

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>