这是我收到的错误:
Warning: Parameter 2 to mysqli_stmt::bind_param() expected to be a
reference, value given
码:
$con = new MysqLi('localhost',USER,PASS,DBS);
if(MysqLi_connect_errno()) {
error(MysqLi_connect_errno());
}
$con -> set_charset("utf8");
/*inside*/
$type='';
$query='SELECT bugID FROM bug';
if(!empty($_GET['cena'])) {
$build[]='uCena=?';
$type.='i';
$val[]=$_GET['cena'];
}
if(!empty($_GET['popust'])) {
$build[]='uPopust=?';
$type.='i';
$val[]=$_GET['popust'];
}
if(!empty($build)) {
echo $query .= ' WHERE '.implode(' AND ',$build);
}
$new = array_merge(array($type),$val);
foreach($new as $key => $value)
{
$tmp[$key]=&$new[$key];
}
echo '<br/><br/>';
foreach ($new as $new ){
echo "$new<br/>";
}
if ($count = $con->prepare($query)) {
call_user_func_array(array($count,'bind_param'),$tmp);
$count->execute();
$cres = $count->fetch_row();
$count -> close();
} else error($con->error);
/*inside*/
$con -> close();
解决方法:
我很抱歉这样说,但你的代码很糟糕.它是不可读的,并且在生产环境中很难维护.
一个例子:你在哪里使用这些行:
foreach($new as $key => $value)
{
$tmp[$key]=&$new[$key];
}
你可以使用:
foreach($new as $key => $value)
{
$tmp[$key]= $value;
}
哪个会显示你对foreach声明的理解.此外,使用比$tmp和$new更多的描述性变量名称可以提高代码的可读性.您的代码还有很多问题,但让我们关注这个问题.
主要问题在于这一行:
if ($count = $con->prepare($query)) {
这一行:
call_user_func_array(array($count,'bind_param'),$tmp);
MysqLi :: prepare()返回一个MysqLi_statement(如here所述),而不是某种计数.如果需要确定参数的数量,请尝试使用$count = count($tmp).
您看到的错误是您使用call_user_func_array()的结果.如PHP.net page on bind_param所述:
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.
Coming to the problem calling MysqLi::bind_param() with a dynamic number of arguments via call_user_func_array() with PHP Version 5.3+, there’s another workaround besides using an extra function to build the references for the array-elements.
You can use Reflection to call MysqLi::bind_param(). When using PHP 5.3+ this saves you about 20-40% Speed compared to passing the array to your own reference-builder-function.
例:
<?PHP
$db = new MysqLi("localhost","root","","tests");
$res = $db->prepare("INSERT INTO test SET foo=?,bar=?");
$refArr = array("si","hello",42);
$ref = new ReflectionClass('MysqLi_stmt');
$method = $ref->getmethod("bind_param");
$method->invokeArgs($res,$refArr);
$res->execute();
?>
希望这可以帮助.