【问题标题】:Loop through database with PHP and show in HTML table使用 PHP 循环访问数据库并在 HTML 表格中显示
【发布时间】:2014-01-16 19:10:08
【问题描述】:

我正在尝试遍历我的数据库并显示所有条目。

这是我的代码:

<?php
        // Create connection
        $con=mysqli_connect("host","username","password","database");

        // Check connection
        if (mysqli_connect_errno($con)) {
            echo "Failed to connect to MySQL: " . mysqli_connect_error();
        }

        //Get number of rows
        $sql="SELECT * FROM TBook";
        $result=mysqli_query($con, $sql);
        $rowcount=mysqli_num_rows($result);

        //Start table
        echo "<table>";
        echo "<tr><th>Date</th><th>Period</th><th>Room</th><th>Teacher Initials</th></tr>";

        // Loop through database
        for ($i = 1; $i < $rowcount; $i++) {
            $row = mysql_fetch_array($result);
            $date = $row['date'];
            $period = $row['period'];
            $room = $row['room'];
            $teacherinitials = $row['teacherinitials'];

        // Show entries
            echo    "<tr>
                <td>".$date."</td>
                <td>".$period."</td>
                <td>".$room."</td>
                <td>".$teacherinitials."</td>
                </tr>";

        }

        echo "</table>"
?> 

但是,当我运行它时,只显示列的标题。

出了什么问题?

【问题讨论】:

  • 如果只返回 1 行,它将永远不会显示 for ($i = 0; $i &lt; $rowcount; $i++) ... 但是您正在组合 MySQLi 和 MySQL:而不是 for ($i = 1; $i &lt; $rowcount; $i++) { $row = mysql_fetch_array($result);,使用 while ($row = $result-&gt;fetch_assoc()) {
  • 你要的是:while ($row = mysql_fetch_array($result)) { .... }
  • 谢谢马克,这解决了它!

标签: php html mysql sql database


【解决方案1】:

也许你可以试试这个代码:

     // Check connection
    if (mysqli_connect_errno($con)) {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }

    //Get number of rows
    $sql="SELECT * FROM TBook";
    $result=mysqli_query($con, $sql);
    $i=1;
    while($row=mysqli_fetch_assoc($result))
    {
        $date[$i] = $row['date'];
        $period[$i] = $row['period'];
        $room[$i] = $row['room'];
        $teacherinitials[$i] = $row['teacherinitials'];
        $i++;
    }  
    //Start table
    echo "<table>";
    echo "<tr><th>Date</th><th>Period</th><th>Room</th><th>Teacher Initials</th></tr>";

    // Loop through the results from the database
    for ($i = 1; $i <=count($date); $i++) 
    {
    // Show entries
        echo    
            "<tr>
            <td>$date[$i]</td>
            <td>$period[$i]</td>
            <td>$room[$i]</td>
            <td>$teacherinitials[$i]</td>
            </tr>";

    }

    echo "</table>"
 ?> 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 2019-10-29
    • 2019-03-17
    • 1970-01-01
    • 2017-12-19
    • 1970-01-01
    相关资源
    最近更新 更多