我可以使用for或while在PHP中循环此代码吗?

时间:2016-03-27 06:42:41

标签: php mysql

<?php
$query = "SELECT bobot FROM `record_result` WHERE `participantid` = $idParticipant AND `questionid` = 1";
$query1 = "SELECT bobot FROM `record_result` WHERE `participantid` = $idParticipant AND `questionid` = 2";
$comments = mysql_query($query);
$comments1 = mysql_query($query1);
while($row = mysql_fetch_array($comments, MYSQL_ASSOC)) {
   $bobot = $row['bobot'];
   $bobot = htmlspecialchars($row['bobot'],ENT_QUOTES);
}
while($row = mysql_fetch_array($comments1, MYSQL_ASSOC)) {
   $bobot1 = $row['bobot'];
   $bobot1 = htmlspecialchars($row['bobot'],ENT_QUOTES);
}
?>

我想让这段代码可以循环直到10.我希望变量不多,例如:$ query,$ query1,$ query2,...,$ query10,$ comments,$ comments1,$ comments2 ,...,$ comments10,$ bobot,$ bobot1,$ bobot2,...,$ bobot10。有人帮助我,请...

1 个答案:

答案 0 :(得分:0)

你快到了。但我必须提到您应该开始使用prepared statements参数化查询,而不是手动构建查询。

$id = 1;
while($id <= 10) {
   // construct your query
   $query = "SELECT bobot FROM `record_result` WHERE `participantid` = $idParticipant AND `questionid` = $id";
   // execute and get results
   $comments = mysql_query($query);

   // iterate over records in result
   while($row = mysql_fetch_array($comments, MYSQL_ASSOC)) {
      $bobot = $row['bobot'];
      $bobot = htmlspecialchars($row['bobot'],ENT_QUOTES);
   }

   // increment the id for next cycle through the loop
   $id = $id + 1;
}