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

标签 php mysql

我目前正在编写一个非常基本的 PHP api,它使用 MySql 数据库进行身份验证和记录用户数据。我使用准备好的语句来避免 MySql 注入(inject)。我试图创建一个通用函数来处理和执行准备好的查询,如下所示:

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 函数。

最佳答案

可以使用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 希望参数是引用,您必须调整设置$param_args 的方式:

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

关于php - 将数组作为参数列表传递给非用户定义的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33178704/

相关文章:

php - AnViz 设备的校验和算法是什么?

php - 如何通过返回表单页面来更新表中的特定行?

java - swing 将数据从 mysql 数据库检索到文本字段

支持远程和本地访问的 Mysql

mysql - 我如何使用 golang go-sqlmock sqlmock 空集

mysql - 连接字符串以指定字段名称

php - 购买元素的数据库关系

php - Laravel - 传递多个变量以查看

php 或 mysql 在导入数据库时​​卡住

php - 如何获取在 mysql 中使用 "REPLACE INTO"时受到影响的行的 ID