2013-02-08 111 views
0

Im建立一個網站,它將返回mysql的結果並將它們顯示在網頁上。 我在將數據存儲在mysql中或檢索數據 並將其顯示在網頁上沒有問題。 當數據返回到頁面時,我想將它存儲在一個表中並運行一個循環,以便每個記錄都會有一個像列表號一樣向下遞增的數字。 任何幫助,將不勝感激。 我一直運行到我的代碼錯誤:顯示來自mysql的數據,在表中顯示

<?php 
    $con = mysql_connect("localhost","root",""); 
    if (!$con) 
     { 
     die('Could not connect: ' . mysql_error()); 
     } 

    mysql_select_db("forloops", $con); 

    $result = mysql_query("SELECT * FROM userinfo ORDER BY age DESC"); 

    echo "<table border='1'> 
    <tr> 
     <th>Position</th> 
    <th>Firstname</th> 
    <th>Lastname</th> 
    <th>Age</th> 
    </tr>"; 
    $counter = 0; 
     $position= 0; 
    $row = mysql_fetch_array($result); 

    if($counter <=10){ 

      echo "<tr>"; 
         echo "<td>" . $position . "</td>"; 
      echo "<td>" . $row['firstname'] . "</td>"; 
      echo "<td>" . $row['lastname'] . "</td>"; 
      echo "<td>" . $row['age'] . "</td>"; 
      echo "</tr>"; 
      $counter++; 
      } 
    echo "</table>"; 
    mysql_close($con); 
    ?> 
+0

你得到了什麼錯誤? – dziwna 2013-02-08 13:46:49

回答

0

與您現有的代碼的問題是,你只能從查詢獲取的第一行,看看我怎麼樣了向下跌破它:

echo "<table border='1'> 
<tr> 
    <th>Position</th> 
<th>Firstname</th> 
<th>Lastname</th> 
<th>Age</th> 
</tr>"; 
$counter = 0; 
    $position= 0; 

while ($row = mysql_fetch_array($result)) { // This is new code 
    if($counter <=10){ 

     echo "<tr>"; 
        echo "<td>" . $position . "</td>"; 
     echo "<td>" . $row['firstname'] . "</td>"; 
     echo "<td>" . $row['lastname'] . "</td>"; 
     echo "<td>" . $row['age'] . "</td>"; 
     echo "</tr>"; 
     $counter++; 
    } 
} // This is new code 
echo "</table>"; 
mysql_close($con); 
?> 

如果你發現,我已經創建了周圍的錶行<tr>和細胞<td>的呼應循環。

這個while循環將遍歷查詢返回的每一行。

0

如果你從數據庫中一個以上的結果,你應該使用:

while ($row = mysql_fetch_array($result)) { 
//process one row 
} 

用自己的方式,$行是永遠不變的。 其次,如果我看到正確的,你不增加$位置變量。

+0

這正是我已經解釋過的。 – 2013-02-08 13:35:49

+0

我在寫文章的同時發佈它,所以很抱歉加倍:) – 2013-02-08 13:39:34