php - 如何从 PDO 的 fetchAll 结果中获取列名?

标签 php pdo

我创建了一个代码来显示表格

$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/

相关文章:

PHP/SQL - 无法打开流 : No such file or directory

mysql - 计数并执行插入或更新

php - "The active result contains no fields"将 PDO 与 MS SQL 结合使用

php - 使用 PDO 和 bootstrap 向现有 html 表添加新行

PHP 查询 - 当用户 ID 存储在另一个表中时,如何添加新列并在表中插入用户信息?

php - 收件箱/消息数据模型

php - 在其自己的类中设置从 PDO 返回的对象

php - 按日期排序并按 ID 分组

php - 如何每天自动运行php脚本?

php - 禁用 MySQL 并发