2013-10-01 29 views
0

我正在嘗試創建一個結果表。HTML中的PHP自動增加表

這裏是什麼樣的表看起來像至今一個形象:

img

<?php 
     $row = mysql_query("SELECT * FROM table ORDER BY Votes DESC LIMIT 5"); 
     while($sql = mysql_fetch_assoc($row)){ 
     ?> 
     <tr> 
      <td width="5%" align="center"><?php $rank=1; echo $rank;?></td> 
      <td width="15%" align="center"><img src="/pictures/<?php echo $sql['Picture']; ?>.png" height="50%"></td> 
      <td width="7%" align="center"><?php echo $sql['Votes']; ?></td> 
     </tr> 
       <?php } ?> 

也就是說到目前爲止的代碼。我試圖做到這一點,排名會自動增加。順便說一句,排名不是來自數據庫,但我只是希望它從1開始,然後增加。請幫幫我。

回答

0
<?php 
    $row = mysql_query("SELECT * FROM table ORDER BY Votes DESC LIMIT 5"); 

    $rank = 0; // default rank 
    while($sql = mysql_fetch_assoc($row)) 
    { 
     $rank += 1; // increase 
    ?> 
     <tr> 
      <td width="5%" align="center"><?php echo $rank;?></td> 
      <td width="15%" align="center"><img src="/pictures/<?php echo $sql['Picture']; ?>.png" height="50%"></td> 
      <td width="7%" align="center"><?php echo $sql['Votes']; ?></td> 
     </tr> 
<?php } ?> 
+0

非常感謝。我沒有意識到這會很簡單。 –

0

您的問題是在$秩變量在while循環

<td width="5%" align="center"><?php $rank=1; echo $rank; //this line ?></td> 

所以,你需要將其移出循環的聲明,因爲它會設置爲1時再次循環繼續(那爲什麼總是顯示1)

要修正這個問題,你應該這樣做

<?php 
    $row = mysql_query("SELECT * FROM table ORDER BY Votes DESC LIMIT 5"); 
    $rank = 1; // declare rank here 
    while($sql = mysql_fetch_assoc($row)){ 
    ?> 
    <tr> 
     <td width="5%" align="center"><?php echo $rank++; // increase rank by 1 each times the loop run ?></td> 
     <td width="15%" align="center"><img src="/pictures/<?php echo $sql['Picture']; ?>.png" height="50%"></td> 
     <td width="7%" align="center"><?php echo $sql['Votes']; ?></td> 
    </tr> 
<?php } ?> 

希望這個幫助!