绑定结果在MySQLi中

时间:2014-07-16 02:32:03

标签: php mysqli

在下面的代码中,如果我尝试在使用不同参数集连续两次执行后获取结果,则会显示相同的结果集(第一个两次),而不是显示具有不同参数的结果。我该怎么办?另外,在PHP手册中,$ sqli-> bind_results()放在$ sqli-> execute()之后,它是否总是强制的,或者在$ sqli-&gt之前放置$ sqli-> bind_results()也是有效的;执行() ?

<?php
  $mysqli = new mysqli("localhost","root","","test");

  /*check connection*/
  if(mysqli_connect_errno())
  {
    printf("connection failed: %s\n",mysqli_connect_error());
    exit();
  }

  /*create prapared statement*/

  $sqli = $mysqli->prepare("select post_id from posts where id=?"); 

  /*bind params*/
  $sqli->bind_param('i',$id);


  /*set params*/
  $id =1;

  /*execute prapared statement*/
  $sqli->execute();

  /*bind results*/
  $sqli->bind_result($post_id);

  while($sqli->fetch())
  {
    echo ' '.$post_id;

  }

  echo '<br/>fetch new record<br/>';

  /*set params*/
  $id =2;

  /*execute prapared statement*/
  $sqli->execute();


  while($sqli->fetch())
  {
    echo ' '.$post_id;

  }   

执行循环: *

Scene1:重复调用bind_result($ post_id)

<?php
  $mysqli = new mysqli("localhost","root","","test");

  /*check connection*/
  if(mysqli_connect_errno())
  {
    printf("connection failed: %s\n",mysqli_connect_error());
    exit();
  }

  /*create prapared statement*/

  $sqli = $mysqli->prepare("select post_id from posts where id=?"); 

  /*bind params*/
  $sqli->bind_param('i',$id);

  for($x=0;$x<1000;$x++)
  {

    $id =$x;


    $sqli->execute();

    /*****bind results*****/

    $sqli->bind_result($post_id);

    while($sqli->fetch())
    {
      echo ' '.$post_id;

    }
  }
?>

Scene2:调用bind_result($ post_id)一次

<?php
  $mysqli = new mysqli("localhost","root","","test");

  /*check connection*/
  if(mysqli_connect_errno())
  {
    printf("connection failed: %s\n",mysqli_connect_error());
    exit();
  }

  /*create prapared statement*/

  $sqli = $mysqli->prepare("select post_id from posts where id=?"); 

  /*bind params*/
  $sqli->bind_param('i',$id);

  /*****bind results*****/

  $sqli->bind_result($post_id);

  for($x=0;$x<1000;$x++)
  {

    $id =$x;


    $sqli->execute();


    while($sqli->fetch())
    {
      echo ' '.$post_id;

    }
  }
?>

现在,作为PHP手册,应该在execute()之后使用bind_result(),但是如上面的scene1所示,这将调用&#34; bind_result()&#34;反复而在scene2中,它只被调用一次,但仍然表现良好。哪种方法更好? scen2有效吗?

1 个答案:

答案 0 :(得分:0)

是的,您需要在每次 bind_result之后运行execute

来自the manual ...

  

请注意,所有列必须在mysqli_stmt_execute()之后和调用mysqli_stmt_fetch()之前绑定。

所以,你只是错过了对bind_result ...

的第二次(必需)调用
$id = 2;
$sqli->execute();
$sqli->bind_result($post_id);