Search code examples
phpmysqldatabasehtml-table

Show values from a MySQL database table inside a HTML table on a webpage


I want to retrieve the values from a database table and show them in a html table in a page. I already searched for this but I couldn't find the answer, although this surely is something easy (this should be the basics of databases lol). I guess the terms I've searched are misleading. The database table name is tickets, it has 6 fields right now (submission_id, formID, IP, name, email and message) but should have another field called ticket_number. How can I get it to show all the values from the db in a html table like this:

<table border="1">
  <tr>
    <th>Submission ID</th>
    <th>Form ID</th>
    <th>IP</th>
    <th>Name</th>
    <th>E-mail</th>
    <th>Message</th>
  </tr>
  <tr>
    <td>123456789</td>
    <td>12345</td>
    <td>123.555.789</td>
    <td>John Johnny</td>
    <td>[email protected]</td>
    <td>This is the message John sent you</td>
  </tr>
</table>

And then all the other values below 'john'.


Solution

  • Get the data first and then display it later.

    <?php
    $con = mysqli_connect("localhost","peter","abc123","my_db");
    $result = mysqli_query($con,"SELECT * FROM Persons LIMIT 50");
    $data = $result->fetch_all(MYSQLI_ASSOC);
    ?>
    
    <table border="1">
      <tr>
        <th>Firstname</th>
        <th>Lastname</th>
      </tr>
      <?php foreach($data as $row): ?>
      <tr>
        <td><?= htmlspecialchars($row['first_name']) ?></td>
        <td><?= htmlspecialchars($row['last_name']) ?></td>
      </tr>
      <?php endforeach ?>
    </table>