dongqindan4406 2014-07-09 10:12
浏览 78
已采纳

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

sample1:

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

  /*check connection*/
  if(mysqli_connect_errno())
  {
    printf("connection failed: %s
",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
",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/>';
      }     

   }     

  }


?>    

Is there any performance difference in both the ways how parameters are bound (shown in bold in sample1 and sample2) or MySQLi automatically handles this? In sample1,although it is unnecessary bind_param is included inside the while loop.

  • 写回答

1条回答 默认 最新

  • drurhg37071 2014-07-09 10:17
    关注

    Calling a function repeatedly is more expensive than not calling it repeatedly, so there should be a small performance gain in the second version. There's no point in calling bind_param inside the loop since it's unnecessary -- the first call binds to a reference to the variable, so all you have to do is reassign the variable.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀