1

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?

2
  • What do you mean by header? What would be the header name, the selected table? Commented Nov 19, 2019 at 8:44
  • Yes, header for selected table. The code i show is header for 'Country' table. Commented Nov 19, 2019 at 8:46

1 Answer 1

2

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.