Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
402 views
in Technique[技术] by (71.8m points)

php - 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();

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are many duplicated questions but all answers are beyond any reason, offering complicated solutions involving running extra queries etc.

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]) : [];

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...