0

mysql から結果を返し、それらを Web ページに表示する Web サイトを構築しています。データをmysqlに保存したり、データを取得してWebページに表示したりすることに問題はありません。データがページに返されたら、それをテーブルに格納してループを実行し、レコードごとにリスト番号のように数字が増加するようにします。どんな助けでも大歓迎です。コードでエラーが発生し続けます。

<?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);
    ?> 
4

2 に答える 2

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ループは、クエリから返された各行を通過します。

于 2013-02-08T13:29:57.057 に答える
0

データベースからの結果が複数ある場合は、次を使用する必要があります。

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

あなたのやり方で、 $row は常に同じです。第二に、私が正しければ、$position 変数を増やす必要はありません。

于 2013-02-08T13:35:14.410 に答える