我目前正在编写一个非常基本的PHP API,它使用MySql数据库进行身份验证和记录用户数据。我使用准备好的语句来避免MySql注入。我试图做一个泛型函数来处理和执行准备好的查询如下:将数组作为参数列表传递给非用户定义函数
function query_prepared($sql, $type){//$type here is the string containing the characters of the type of the data to bind - e.g. 'sss' for string, string, string
$args = func_get_args();
$param_args = array();
for($i = 2; $i < count($args); $i++){
$param_args[$i - 2] = $args[$i];
}//the version of PHP I am using does not support variable length arguments so I have to store all of the arguments but the sql statement and parameter types in an array ($param_args)
$con = connect();//connects to the database
$statement = $con->prepare($sql);
if(!$statement)
error("Error while querying database. " . mysqli_error($con), ERR_QUERY_DB);
$statement->bind_param($type, $param_args);//<-- My problem is here - the bind_param function is supposed to pass arguments like this, $statement->bind_param($type, $var0, $var1, $var2...) but I only have an array of $var0, $var1, $var2... so it attempts to convert my array to a string before passing it to the bind_param function.
$statement->execute();
$statement->bind_result($result);
$rows = array();
$i = 0;
while($row = $result->fetch())
$rows[$i++] = $row;
$con->close();
return $rows;
}
我已经做了一些阅读,发现call_user_func_array
功能,但这显然不会在这种情况下工作。
有没有办法将我的数组($ param_args)作为可变长度参数传递给bind_params函数。
你的阵列应该像'关联“:PARAM” =>'value'' –
你的意思是“*显然*在这种情况下不起作用”? –
@AlanMachado我该怎么做? – rodit