2009-06-08 106 views
0

我試圖從不斷重演,因爲在循環在相同的數據停止下表中的數據,崩潰的瀏覽器:停止連續表生成

這裏的查詢:

$posts = mysqli_fetch_assoc(mysqli_query($db, "SELECT * from tbl_bugresponse WHERE bugid = $id ORDER BY time")); 

這裏的表代碼:

<table width="100%" class="tborder"> 
    <tr> 
     <th class="tcat">Name</th> 
     <th class="tcat">Reply</th> 
    </tr> 
    <?php 
     $colour="1"; 
     while($posts) { 
      if($colour == "1"){ 
       echo ("<tr class='alt1'>"); 
       $f1 = $posts['by']; 
       $f2 = $posts['content']; 
       $colour = "2"; 
      } 
      else { 
       echo "<tr class='alt2'>"; 
       $f1 = $posts['by']; 
       $f2 = $posts['content']; 
       $colour = "1"; 
      } 
      ?> 
      <td><?php echo $f1; ?></td> 
      <td><?php echo $f2; ?></td> 
     </tr> 
     <?}?> 
</table> 

請注意,我使用mysqli不是mysql。

回答

4

您沒有完成結果集。 mysqli_query得到你的結果集,並且mysqli_fetch_assoc通過它。你需要像這樣的東西:

$results = mysqli_query($db, "SELECT * from tbl_bugresponse WHERE bugid = $id ORDER BY time"); 
while ($posts = mysqli_fetch_assoc($results)) { 
    // table construction code goes here 
} 
4

問題是while($posts){行。

你正在寫代碼說:「繼續下去,直到有人把帖子變量設置爲空或者假」,但你永遠不會碰它......所以它會一直持續下去。

更新

只好再看看你的查詢,它看起來像你有困惑,它是如何工作的。下面是它應該是什麼樣子:

$result = mysqli_query($db, "SELECT * from tbl_bugresponse WHERE bugid = $id ORDER BY time"); 
... 
$post = mysql_fetch_assoc($result); // fetch first row 
while($post) { // will keep going until $post gets set to null or false 
    ... 
    $post = mysql_fetch_assoc($result); // fetch next row and re-run the loop 
} 

你會注意到,mysqli_query呼叫已被分離出來。 mysqli_query所做的是運行數據庫查詢,然後爲查詢返回的行列表提供一個「句柄」。這是常見的混淆之處,因爲大多數人期望它能夠爲它們提供所有行的數組,而不是「句柄」。

然後您必須致電mysql_fetch_assoc以獲得列表中的第一行,使用它執行某些操作,然後再次調用mysql_fetch_assoc以獲取下一行。

當用完行時,mysql_fetch_assoc將返回null而不是有效行,因此,您可以檢查完成時間並停止循環。

+0

我會如何把該代碼? – bear 2009-06-08 21:29:12