bind_param PHP 的以下方法有什么区别
What is the difference between the following to methods for bind_param PHP
我刚刚不再使用单例方法并开始使用准备好的语句...我正在绞尽脑汁思考为什么其中一个版本有效而另一个版本无效,对我来说,它们似乎是同一件事...我真的希望它以第二种方式工作,以实现我的最终目标。
这个有效:
call_user_func_array(array($stmt, 'bind_param'), array("i", 2));
这不是:
$params = array("i", 2);
call_user_func_array(array($stmt, 'bind_param'), $params);
您可能收到类似
的错误消息
mysqli_stmt::bind_param() expected to be a reference, value given in...
问题是 PHP 5.3+ 中的 bind_param()
需要数组值作为参考,而 5.2 使用实数值。
来自docs:
Care must be taken when using mysqli_stmt_bind_param() in conjunction with call_user_func_array(). Note that mysqli_stmt_bind_param() requires parameters to be passed by reference, whereas call_user_func_array() can accept as a parameter a list of variables that can represent references or values (ref).
一个解决方案是创建一个引用数组
$params = array("i", 2);
$tmp = array();
foreach($params as $key => $value) {
$tmp[$key] = &$params[$key];
}
call_user_func_array(array($stmt, 'bind_param'), $tmp);
另一个类似的solution是
function refValues($arr){
if (strnatcmp(phpversion(),'5.3') >= 0) //Reference is required for PHP 5.3+
{
$refs = array();
foreach($arr as $key => $value)
$refs[$key] = &$arr[$key];
return $refs;
}
return $arr;
}
$params = array("i", 2);
call_user_func_array(array($stmt, 'bind_param'), refValues($params));
我刚刚不再使用单例方法并开始使用准备好的语句...我正在绞尽脑汁思考为什么其中一个版本有效而另一个版本无效,对我来说,它们似乎是同一件事...我真的希望它以第二种方式工作,以实现我的最终目标。
这个有效:
call_user_func_array(array($stmt, 'bind_param'), array("i", 2));
这不是:
$params = array("i", 2);
call_user_func_array(array($stmt, 'bind_param'), $params);
您可能收到类似
的错误消息mysqli_stmt::bind_param() expected to be a reference, value given in...
问题是 PHP 5.3+ 中的 bind_param()
需要数组值作为参考,而 5.2 使用实数值。
来自docs:
Care must be taken when using mysqli_stmt_bind_param() in conjunction with call_user_func_array(). Note that mysqli_stmt_bind_param() requires parameters to be passed by reference, whereas call_user_func_array() can accept as a parameter a list of variables that can represent references or values (ref).
一个解决方案是创建一个引用数组
$params = array("i", 2);
$tmp = array();
foreach($params as $key => $value) {
$tmp[$key] = &$params[$key];
}
call_user_func_array(array($stmt, 'bind_param'), $tmp);
另一个类似的solution是
function refValues($arr){
if (strnatcmp(phpversion(),'5.3') >= 0) //Reference is required for PHP 5.3+
{
$refs = array();
foreach($arr as $key => $value)
$refs[$key] = &$arr[$key];
return $refs;
}
return $arr;
}
$params = array("i", 2);
call_user_func_array(array($stmt, 'bind_param'), refValues($params));