sprintf and mysql_real_escape_string all in one function

Well as many php developers will know, there is the arduous task of having to sanitize all of your data before actually being able to add it to your queries for running in MySQL. So I decided to make a small function that would basically be a clone of the sprintf function, with the added bonus of running the mysql_real_escape_string on all of the arguments passed to it

function mressf()
    $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;

You would then call it as you would with your regular sprintf function such as

echo mressf("SELECT * FROM `table` WHERE `name` = '%s' AND `password` = '%s'", 'username', 'pass');

which would return

SELECT * FROM `table` WHERE `name` = 'username' AND `password` = 'pass'

Tags: , , ,

Leave a Reply

You must be logged in to post a comment.