$sql = "SELECT * FROM table WHERE field1='%s' AND field2 ='%s'";
This form is used in conjuntion with sprintf. You could create your own wrapper function to deal with escaping arguments based on the sprintf format specifiers, and then passing the result on to sprintf, but it is an inefficient approach and I believe it should be avoided. E.g
function escapeQuery($qry, $args) {
// Do note that sprintf takes more format specifiers than just %s and %d...
$p = '#(?<!%)(?:%|%{3}|%{5})(d|s)#';
if (preg_match_all($p, $qry, $match)) {
if (($argCount = count($match[1])) != count($args)) {
error_log('Argument and value count mismatch for ' . $qry . ' with ' . print_r($args,1));
}
else {
for ($i = 0; $i < $argCount; ++$i) {
switch ($match[1][$i]) {
case 'd':
$args[$i] = (int) $args[$i];
break;
case 's':
$args[$i] = mysql_real_escape_string($args[$i]);
break;
default:
error_log('Argument type not recognized ' . $match[1][$i]);
$args[$i] = mysql_real_escape_string($args[$i]);
}
}
}
array_unshift($args, $qry);
return call_user_func_array('sprintf', $args);
}
}
$qry = "SELECT * FROM table WHERE field1='%s' AND field2=%d AND field3='%%s' and field4='%%%d'";
$args = array("I'm a string", 5, 80);
echo escapeQuery($qry, $args);
The other and better way to go is with prepared statements, using either mysqli or PDO.
If you go down the mysqli road, you will probably want something to automate result parameter binding
$meta = $stmt->result_metadata();
if ($meta) {
$fields = $meta->fetch_fields();
$meta->close();
$result = array();
foreach ($fields as $f) {
$bind[] = &$row[$f->name];
}
call_user_func_array(array(&$stmt, 'bind_result'), $bind);
while($stmt->fetch()) {
// $k will be the fieldName, $v its value
foreach($row as $k => $v)