Php 将数组值分离为多个参数
我在自定义数据库类中创建了一个函数。该函数用于接受参数化SQL,清理输入并执行它 我唯一的问题是最后一行没有注释。我有一个数组类型的变量,但我需要将数组中的每个值作为单独的参数传递。我该怎么做呢Php 将数组值分离为多个参数,php,arrays,function,arguments,sanitization,Php,Arrays,Function,Arguments,Sanitization,我在自定义数据库类中创建了一个函数。该函数用于接受参数化SQL,清理输入并执行它 我唯一的问题是最后一行没有注释。我有一个数组类型的变量,但我需要将数组中的每个值作为单独的参数传递。我该怎么做呢 function do_query($sql, $values){ if(!isset($this->connect_error)){ if(tg_debug == true){ print "Query Executing! <br />
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();
}
}
函数do\u查询($sql,$value){
如果(!isset($this->connect_error)){
if(tg_debug==true){
打印“正在执行查询!
”;
}
$num_vals=计数($value);
$i=0;
$type=“”;
而($i<$num\u vals){
if(is_int($values[$i])==true)
$type.=“i”;
elseif(is_字符串($values[$i])==true)
$type.=“s”;
$i++;
}
$i=0;
而($i<$num\u vals){
//这里有保安人员。。。
$values[$i]=$this->escape_字符串($values[$i]);
$i++;
}
$expr=$this->prepare($sql);
打印(价值);
//$values仍然是一个数组,提取值并转换为单独的参数
$expr->bind_参数($type,$value);
//$expr->execute();
}
}
查询示例:$class->do_query(“插入到表(id,value)值(?,)”,数组(3,“这是一个测试”)代码>使用
您可以使用:
当将添加到语言中时,这将大大简化,应在5.6中进行:
$exp->bind_param($type, ...$values);
使用foreach循环迭代第二个参数,然后在循环中使用bind_参数,然后在endforeach之后执行,如果您的意思是:$expr->bind_参数($type);foreach($val形式的值){$expr->bind_param($val);}
这不起作用。我得到了一个错误的参数计数警告。请参阅php.net上关于如何使用ReflectionClass来实现这一点的。
$args = $values;
array_unshift($args, $type);
call_user_func_array(array($expr, 'bind_param'), $args);
$exp->bind_param($type, ...$values);