显示mysql中的数据,将其显示在表中

时间:2013-02-08 13:26:25

标签: php

我正在建立一个网站,它将从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);
    ?> 

2 个答案:

答案 0 :(得分: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循环将遍历查询返回的每一行。

答案 1 :(得分:0)

如果您有多个来自数据库的结果,则应使用:

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

用你的方式,$ row总是一样的。 其次,如果我看到了正确的话,你就不会增加$ position变量。

相关问题