This is an old-style PHP4/MySQL4 prepared statement emulation.
A couple of quick and dirty functions that I put together some years ago.
I kept recycling them for small projects when true prepared statements were not available.
They assume there's just a global "automatic" connection (needed for "real" escaping fitting database charset), but this can be easily adjusted by passing the connection handle around to both or encapsulating them in a class holding the connection as a property.
Typical usage:
mysql_query(
db_prepare_sql('INSERT INTO mytable (first_name, last_name, phone)
values(?, ?, ?)',
$_POST['first_name'], $_POST['last_name'], $_POST['phone']
));
Source code:
function db_prepare_sql($sql, $params) {
static $replacement =
'db_esc($idx < $paramsCount ? $params[$idx++] : null)';
$numArgs = func_num_args();
$idx = 0;
if($numArgs == 1) {
$paramsCount = 0;
$idx = 0;
} else if($numArgs>2 || !is_array($params)) {
$params = func_get_args();
$paramsCount = $numArgs;
++$idx;
} else {
$paramsCount = count($params);
}
return preg_replace('/\?/e', $replacement, $sql);
}
function db_esc($unescaped) {
if(is_array($unescaped)) {
$res = array();
foreach($unescaped as $unescapedItem) {
$res[] = db_esc($unescapedItem);
}
return join(',', $res);
}
return ($unescaped === null)
? 'NULL'
: ((is_numeric($unescaped) && !($unescaped{0} === '0' && strlen($unescaped) > 1) )
? $unescaped
: "'" . mysql_real_escape_string($unescaped) ."'")
;
}
Cheers
--
*
hackademix.net*
There's a browser safer than Firefox... Firefox, with NoScript