2016-03-27 96 views
0
<?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。有人帮助我,请...我可以在PHP中使用for循环这段代码吗?

回答

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; 
} 
+0

谢谢你帮我,但我还是发现了一个错误“警告:mysql_fetch_array()预计参数1是资源,布尔在给定的”关于脚本“,而($行= mysql_fetch_array($意见,MYSQL_ASSOC) )” –

相关问题