note 81188 deleted from function.mysql-query by philip
| From: | philip@php.net | Date: | Fri, 04 Sep 2015 19:13:32 +0000 |
| Subject: | note 81188 deleted from function.mysql-query by philip | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-203632@lists.php.net to get a copy of this message | ||
Note Submitter: sk89q
----
sprintf+mysql_query which auto-escapes.
Usage:
<?php
$db->queryf("SELECT
m.name FROM
test.members WHERE name=%s OR id=%d OR
sex IN (%a)", "Evil 'injection'", 'NaN',
array('male', 'female', 'both', 'other', "Alien
quote'man"));
?>
To be put into a class, and don't forget to change the $this->query() and $this->escape()
functions accordingly.
<?php
function queryf($sql)
{
$args = func_get_args();
@array_shift($args);
$this->queryf_args = $args;
$this->queryf_i = 0;
$query = preg_replace_callback("#%(.)#", array($this, 'queryf_format'),
$sql);
return $this->query($query);
}
function queryf_format($m)
{
$args = $this->queryf_args;
$i = &$this->queryf_i;
switch($m[1])
{
case '%':
return "%";
case 'a':
$s = array();
$arr = $args[$i++];
foreach($arr as $x)
{
$s[] = "'".$this->escape($x)."'";
}
return implode(",", $s);;=
case 's':
return "'".$this->escape($args[$i++])."'";
case 'd':
return "".intval($args[$i++])."";
default:
trigger_error("Bad type specifier: {$m[1]}", E_USER_ERROR);
}
}
?>