MySQLi bind_param()引用

时间:2013-08-12 21:12:11

标签: php mysqli

我正在尝试将几个参数动态传递给bind_param()函数。

以下是我收到的错误:

  

警告:参数2到mysqli_stmt :: bind_param()应该是一个   参考,给定值

CODE:

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

1 个答案:

答案 0 :(得分:5)

我很抱歉这样说,但你的代码很糟糕。它是不可读的,并且很难在生产环境中维护。

一个例子:你在哪里使用这些行:

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

所述
  

将mysqli_stmt_bind_param()与call_user_func_array()结合使用时必须小心。请注意,mysqli_stmt_bind_param()需要通过引用传递参数,而call_user_func_array()可以接受可以表示引用或值的变量列表作为参数。

同一页面的评论中提供了最佳解决方案:

  

通过使用PHP Version 5.3+的call_user_func_array()调用带有动态数量参数的mysqli :: bind_param()的问题,除了使用额外的函数来构建数组元素的引用之外,还有另一种解决方法。   您可以使用Reflection来调用mysqli :: bind_param()。使用PHP 5.3+时,与将数组传递给您自己的reference-builder-function相比,这可以节省大约20-40%的速度。

示例:

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

希望这有帮助。