如何从 PDO 的 fetchAll 结果中获取列名? [英] How to get column names from PDO's fetchAll result?
问题描述
我创建了一个代码以从表格中显示
I create a code to display from a table
$sql = "SELECT * FROM table";
$stmt = $dbcon->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll();
为了显示结果,我使用以下 ode:
to display the result, I use the following ode:
<?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 } ?>
有什么办法,表格可以带表头显示?
Is there any way, the table can be displayed with the header?
推荐答案
有很多重复的问题,但所有的答案都超出了任何原因,提供了复杂的解决方案,包括运行额外的查询等.
There are many duplicated questions but all answers are beyond any reason, offering complicated solutions involving running extra queries etc.
虽然解决方案就在这里:使用 fetchAll()
时,您已经在 $result
变量中拥有所有列标题
While the solution is right here: when using fetchAll()
, you already have all the column headers in the $result
variable
$headerNames = $result ? array_keys($result[0]) : [];
现在你可以在 $colmnNames
上 foreach 来获取表头,在 $result 上 foreach 来显示结果.
now you can foreach over $coulmnNames
to get the table header and the foreach over $result to display the results.
<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>
这篇关于如何从 PDO 的 fetchAll 结果中获取列名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!