php - 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>";
解决方案
使用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>";
}
推荐阅读
- linux - 致命错误:kdecoration.h:没有这样的文件或目录
- asp.net-core-mvc - 想要一个通用的 EnterpriseLibrary for .NET Core MVC(通用数据库文件)
- go - 切片索引奇怪的边缘情况
- javascript - 基于另一个对象的值访问对象的属性
- scala - 带有 postfixOps 的 Scala 映射
- javascript - 在 React 中为嵌套组件导出 Hooks?
- batch-file - 用于启动新 javaw 进程的批处理文件未按预期工作
- go - 如何在golang的x509证书中解码复合自定义扩展?使用当前代码错误是:asn1:结构错误:序列标签不匹配
- python - 通过 netfilter 钩子修改后的 Tcp 虚假重传
- python - 如何使 GTKOverlay 不会将所有交互从小部件中带走?