我创建了一个代码来显示表格
$sql = "SELECT * FROM table";
$stmt = $dbcon->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll();
为了显示结果,我使用以下代码:
<?php foreach($result as $readrow){ ?>
<div class="table-row">
<td><?php echo $readrow['id'];?></td>
<td><?php echo $readrow['area'];?></td>
<td><?php echo $readrow['color'];?></td>
<?php } ?>
有什么办法,可以让表格带表头显示?
最佳答案
有很多重复的问题,但所有答案都没有任何理由,提供了涉及运行额外查询等的复杂解决方案。
虽然解决方案就在这里:当使用 fetchAll()
时,您已经在 $result
变量中拥有了所有列标题
$headerNames = $result ? array_keys($result[0]) : [];
现在您可以在 $coulmnNames
上使用 foreach 来获取表头,在 $result 上使用 foreach 来显示结果。
<table class='table'>
<tr>
<?php foreach($coulmnNames as $name): ?>
<th><?= $name ?></th>
<?php endforeach ?>
</tr>
<?php foreach($result as $row){ ?>
<tr class="table-row">
<?php foreach($result as $value){ ?>
<td><?= $value ?></td>
</tr>
<?php endforeach ?>
</table>
关于php - 如何从 PDO 的 fetchAll 结果中获取列名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58929766/