【发布时间】:2014-05-29 05:29:34
【问题描述】:
我有一个在自定义数据库类中创建的函数。该函数旨在采用参数化 SQL,清理输入并执行它。
我遇到的唯一问题是最后一个未注释的行。我有一个数组类型的变量,但我需要将数组中的每个值作为单独的参数传递。我该怎么做呢?
function do_query($sql, $values){
if(!isset($this->connect_error)){
if(tg_debug == true){
print "Query Executing! <br />";
}
$num_vals = count($values);
$i = 0;
$type = "";
while($i < $num_vals){
if(is_int($values[$i]) == true)
$type .= "i";
elseif(is_string($values[$i]) == true)
$type .= "s";
$i++;
}
$i = 0;
while($i < $num_vals){
// security stuff goes here...
$values[$i] = $this->escape_string($values[$i]);
$i++;
}
$expr = $this->prepare($sql);
print_r($values);
// $values is still an array, extract values and convert to a seperate argument
$expr->bind_param($type, $value);
//$expr->execute();
}
}
查询示例:$class->do_query("INSERT INTOtable(id, value) VALUES (?, ?)", array(3, "This is a test"));
【问题讨论】:
-
用foreach循环遍历第二个参数,然后在循环中使用bind_param,然后在endforeach之后执行
-
如果您的意思是:
$expr->bind_param($type); foreach($values as $val){ $expr->bind_param($val); }这不起作用。我收到错误参数计数警告。 -
查看 php.net 上的discussion 了解如何使用 ReflectionClass 来实现这一点。
标签: php arrays function arguments sanitization