【问题标题】:Binding parameters in MySQLi prepared statementsMySQLi 准备语句中的绑定参数
【发布时间】:2014-07-09 10:12:14
【问题描述】:

样本1:

<?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/>';
      }     

   }     

  }


?>    

样本2:

<?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/>';
      }     

   }     

  }


?>    

参数绑定方式(在示例 1 和示例 2 中以粗体显示)或 MySQLi 自动处理这两种方式是否存在性能差异?在 sample1 中,虽然没有必要将 bind_param 包含在 while 循环中。

【问题讨论】:

    标签: php mysqli


    【解决方案1】:

    重复调用一个函数比不重复调用代价更高,所以在第二个版本中应该会有一点性能提升。在循环内调用 bind_param 没有任何意义,因为它是不必要的——第一次调用绑定到对变量的引用,所以您所要做的就是重新分配变量。

    【讨论】:

    • $stmt2->bind_result($username) 怎么样,因为每次循环继续时它都会被绑定。 @barbar
    • 同理,只需要做一次,绑定到引用上。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-11
    • 2014-03-20
    • 2011-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多