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条)

报告相同问题?

悬赏问题

  • ¥20 基于决策树的数字信号处理,2ask 2psk 2fsk的代码,检查下报错的原因
  • ¥20 python作业求过程
  • ¥15 wincc已组态的变量过多
  • ¥60 如图:直线与椭圆X轴平行,求直线与椭圆任意一点的相切坐标计算公式
  • ¥50 如何用python使用opencv里的cv::cudacodec::VideoWriter函数对视频进行GPU硬编码
  • ¥100 c#solidworks 二次开发 工程图自动标边线法兰 等折弯尺寸怎么标
  • ¥15 halcon DrawRegion 提示错误
  • ¥15 FastAPI Uvicorn启动显示404
  • ¥15 centos7.9脚本,怎么排除特定的访问记录
  • ¥15 关于#Django#的问题:我的静态文件呢?