MySQLi预处理语句中的绑定参数

时间:2014-07-09 10:12:14

标签: php mysqli

SAMPLE1:

<?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*/

  $stmt1 = $mysqli->prepare("select id from posts");
  $stmt2 =$mysqli->prepare("select username from members where id=?"); 

  test($stmt1,$stmt2);//function call  

  function test($stmt1,$stmt2)
  {
   $stmt1->execute(); 

   $stmt1->store_result();

   $stmt1->bind_result($ID);

   while($stmt1->fetch())
   {
      **/*bind params*/
      $stmt2->bind_param('i',$id); /*HERE,BINDING MANY TIMES*/**

      /*set params*/
      $id =$ID;

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

      /*bind results*/
      $stmt2->bind_result($username);

      while($stmt2->fetch())
      {
        echo 'Username: '.$username.'<br/>';
      }     

   }     

  }


?>    

SAMPLE2:

<?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*/

  $stmt1 = $mysqli->prepare("select id from posts");
  $stmt2 =$mysqli->prepare("select username from members where id=?"); 

  test($stmt1,$stmt2);//function call  

  function test($stmt1,$stmt2)
  {
   $stmt1->execute(); 

   $stmt1->store_result();

   $stmt1->bind_result($ID);

   **/*bind params*/
    $stmt2->bind_param('i',$id); /*HERE,BINDING ONCE*/**

   while($stmt1->fetch())
   {       

      /*set params*/
      $id =$ID;

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

      /*bind results*/
      $stmt2->bind_result($username);

      while($stmt2->fetch())
      {
        echo 'Username: '.$username.'<br/>';
      }     

   }     

  }


?>    

参数绑定的方式是否有任何性能差异(在sample1和sample2中以粗体显示)或MySQLi自动处理此问题?在sample1中,虽然没有必要,但是while循环中包含了bind_param。

1 个答案:

答案 0 :(得分:0)

重复调用函数比不重复调用函数更昂贵,因此在第二个版本中应该有一个小的性能增益。在循环中调用bind_param没有意义,因为它是不必要的 - 第一个调用绑定到对变量的引用,所以你所要做的就是重新分配变量。