2015-10-16 40 views
1

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

+0

你的阵列应该像'关联“:PARAM” =>'value'' –

+0

你的意思是“*显然*在这种情况下不起作用”? –

+0

@AlanMachado我该怎么做? – rodit

回答

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想的参数传递给被引用,你必须调整你如何设置$param_args

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

非常感谢! – rodit

+0

不客气:) –

相关问题