MySQLi bind_param()引用

Bik*_*ohn 2 php mysqli

我试图动态地将几个参数传递给bind_param()函数.

这是我收到的错误:

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

码:

$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();
Run Code Online (Sandbox Code Playgroud)

Luc*_*oed 5

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

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

foreach($new as $key => $value)
{
    $tmp[$key]=&$new[$key];
}
Run Code Online (Sandbox Code Playgroud)

你可以使用:

foreach($new as $key => $value)
{
    $tmp[$key]= $value;
}
Run Code Online (Sandbox Code Playgroud)

哪个会显示你对foreach声明的理解.此外,使用更具描述性的变量名比$tmp$new提高代码的可读性很多.您的代码还有很多问题,但让我们关注这个问题.

主要问题在于这一行:

if ($count = $con->prepare($query)) {
Run Code Online (Sandbox Code Playgroud)

这一行:

call_user_func_array(array($count,'bind_param'),$tmp);
Run Code Online (Sandbox Code Playgroud)

:: mysqli的编制()返回一个mysqli_statement(如描述在这里),而不是某种计数.$count = count($tmp)如果需要确定参数的数量,请尝试使用.

您看到的错误是您使用的结果call_user_func_array().如bind_param上的PHP.net页面所述:

将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();  
?>
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.