我通过向查询函数添加参数来解决了这个问题。
我发现CodeIgniter做得很好,所以我根据自己的喜好进行了调整。
示例:
$result = Database::query('INSERT INTO table (column1,column2,column3) VALUES(?,?,?)',array($value1,$value2,$value3));
public static $bind_marker = '?';
public static function query($query, $binds = FALSE)
{
if($binds !== FALSE)
{
$query = self::compile_binds($query,$binds);
}
}
private static function compile_binds($query, $binds)
{
if(strpos($query, self::$bind_marker) === FALSE)
{
return $query;
}
if(!is_array($binds))
{
$binds = array($binds);
}
$segments = explode(self::$bind_marker, $query);
if(count($binds) >= count($segments))
{
$binds = array_slice($binds, 0, count($segments)-1);
}
$result = $segments[0];
$i = 0;
foreach($binds as $bind)
{
if(is_array($bind))
{
$bind = self::sanitize($bind);
$result .= implode(',',$bind);
}
else
{
$result .= self::sanitize($bind);
}
$result .= $segments[++$i];
}
return $result;
}
public static function sanitize($variable)
{
if(is_array($variable))
{
foreach($variable as &$value)
{
$value = self::sanitize($value);
}
}
elseif(is_string($variable))
{
mysql_real_escape_string($variable);
}
return $variable;
}
我从CodeIgniter的版本中添加的主要功能是可以使用数组作为参数,这对于使用“IN”非常有用:
$parameters = array
(
'admin',
array(1,2,3,4,5)
);
$result = Database::query("SELECT * FROM table WHERE account_type = ? AND account_id IN (?)",$parameters);