doukan5332 2014-09-01 08:06
浏览 28
已采纳

准备好的语句在while循环中由预准备语句生成

so i was just wondering if this is a good practice or not, or for some reason does this type of code affect the speed and functionality of a system ?

$foo = "bar";
$stmt = $db->prepare('SELECT * FROM table WHERE bar=?');
$stmt->bind_param('s',$foo);
$stmt->execute();
$result = $stmt->get_result();
   while($row = $result->fetch_assoc()){
       $val1 = $row['val1'];
       $val2 = $row['val2'];
       echo "<section>";
          $stmt2 = $db->prepare('SELECT * FROM table2 WHERE bar=?');
          $stmt2->bind_param('s',$foo);
          $stmt2->execute();
          $result2 = $stmt2->get_result();
             while($row = $result2->fetch_assoc()){
                 $val1 = $row['val1'];
                 $val2 = $row['val2'];
             }
          $stmt->close();
      echo "</section>";
    }
$stmt->close();

the first statement could generate 50 or more data, that means that another 50 or more stmt will be produced, is this bad ? thanks for the answers.

  • 写回答

2条回答 默认 最新

  • duandu1915 2014-09-01 08:16
    关注

    Every time you prepare a statement, it requires a call to MySQL, which is expensive. If it's the same statement, this is unnecessary and a waste of time.

    You also only need to bind the params once. bind_param associates the parameters with a reference to the variable. So the loop only needs to update the variable's value and call execute.

    In your code, it seems like repeating the inner query every time through the loop is unnecessary. It's not dependent on anything retrieved from the outer query, so it will return the same set of results each time. You should do it once, save the results in an array, and then just loop through the array every time, to avoid hitting the database unnecessarily.

    If that was just an artificial example, and you really do have a dependency between the data returned from the outer query and the parameters to the inner query, you probably should do them as a single query containing a JOIN between the two tables.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥60 pb数据库修改或者求完整pb库存系统,需为pb自带数据库
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路