简体   繁体   English

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

[英]Prepared statement inside while loop generated by prepared statement

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 statement will be produced, is this bad?第一个语句可以生成50个或更多的数据,这意味着会产生另外50个或更多的语句,这不好吗?

Thanks for the answers.感谢您的回答。

Every time you prepare a statement, it requires a call to MySQL, which is expensive.每次准备语句时,都需要调用MySQL,开销很大。 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. bind_param将参数与对变量的引用相关联。 So the loop only needs to update the variable's value and call execute .所以循环只需要更新变量的值并调用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.如果这只是一个人为的示例,并且您确实在从外部查询返回的数据与内部查询的参数之间确实存在依赖关系,那么您可能应该将它们作为包含两个表之间的JOIN的单个查询来执行。

It is generally accepted as bad practice.人们普遍认为这是不好的做法。

You are making the code harder to read and more complicated than it needs to be: increasing the potential for introducing errors in the future and harder for others to understand if they later have to support your code.你让代码更难阅读,也比它需要的更复杂:增加了未来引入错误的可能性,如果他们以后必须支持你的代码,其他人更难理解。

As identified above, you should be using JOIN.如上所述,您应该使用 JOIN。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM