首页 > 解决方案 > PHP "for loop" 标签,从 MySQL 数据库到 HTML Table

问题描述

我从“MySQL 数据库”制作了一个“HTML 表”。我能够执行“php loop for”来检索“cell tag <td>”,但我怎样才能执行“php loop for”来检索“header tag <th>”?谢谢。

这是我的代码:

$query = "SELECT * FROM Landscapes";
$queryResult = $conn->query($query);

echo "<table>";

while ($queryRow = $queryResult->fetch_row()) {
    echo "<tr>";
        for($i = 0; $i < $queryResult->field_count; $i++){
        echo "<td>$queryRow[$i]</td>";
        }
    echo "</tr>";
}

echo "</table>";

标签: phpmysqlfor-loophtml-table

解决方案


使用fetch_assoc()而不是fetch_row(). 它将返回一个关联数组,其键是列名。

当第一行结果你可以再打印列标题。

$firstRow = true;
while ($queryRow = $queryResult->fetch_assoc()) {
    if ($firstRow) {
        echo "<tr>";
        foreach (array_keys($queryRow) as $name)) {
            echo "<th>$name</th>";
        }
        echo "</tr>";
        $firstRow = false;
    }
    echo "<tr>";
    foreach($queryRow as $value){
        echo "<td>$value</td>";
    }
    echo "</tr>";
}

推荐阅读