将数组作为参数列表传递给非用户定义的函数

时间:2015-10-16 20:04:20

标签: php mysql

我目前正在编写一个非常基本的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函数。

1 个答案:

答案 0 :(得分:1)

可以在这里使用call_user_func_array。事实上,这是正确的方法。

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);

注意:bind_param希望args为引用,您必须调整自己设置$param_args的方式:

for($i = 2; $i < count($args); $i++){
    $param_args[] =& $args[$i];
}