2016-03-27 136 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) )」 –

相關問題