Php 将数组作为参数列表传递给非用户定义函数
我目前正在编写一个非常基本的PHPAPI,它使用MySql数据库进行身份验证和记录用户数据。我使用预先准备好的语句来避免MySql注入。我尝试创建一个通用函数来处理和执行准备好的查询,如下所示:Php 将数组作为参数列表传递给非用户定义函数,php,mysql,Php,Mysql,我目前正在编写一个非常基本的PHPAPI,它使用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, strin
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;
}
function query\u prepared($sql,$type){/$type这里是包含要绑定的数据类型的字符的字符串-例如,“sss”表示字符串、字符串、字符串
$args=func_get_args();
$param_args=array();
对于($i=2;$iprepare($sql);
如果(!$语句)
错误(“查询数据库时出错。”.mysqli_error($con),ERR_QUERY_DB);
$statement->bind_-param($type,$param_-args);//bind_-param($type,$var0,$var1,$var2…)但是我只有一个$var0,$var1,$var2…的数组,所以它试图在将数组传递给bind_-param函数之前将其转换为字符串。
$statement->execute();
$statement->bind_result($result);
$rows=array();
$i=0;
而($row=$result->fetch())
$rows[$i++]=$row;
$con->close();
返回$rows;
}
我读了一些书,找到了call\u user\u func\u array
函数,但在这个例子中显然不起作用
是否有任何方法将我的数组($param_args)作为可变长度参数传递给bind_params函数。您可以在此处使用。事实上,这是正确的方法
array_unshift($param_args, $type); // <- Prepend $type to the array so it's passed too
// The 1st parameter is the callback. It's array($object, 'method')
call_user_func_array(array($statement, 'bind_param'), $param_args);
您的数组应该是一个关联数组,如
”:param'=>“value'
您所说的“显然在这个实例中不起作用”是什么意思?@AlanMachado我该怎么做?@RocketHazmat在这种情况下如何使用它?@AlanMachado:这只适用于PDO。这是在使用MySQLi。
for($i = 2; $i < count($args); $i++){
$param_args[] =& $args[$i];
}