Selecting and Displaying Records

A useful output begins with a query and ends with accessible, escaped HTML.

Select only required fields

$stmt = $pdo->query(
    "SELECT activity_id, activity_name, location, capacity
     FROM activities
     ORDER BY activity_name"
);
$activities = $stmt->fetchAll();

Avoid SELECT * when the page needs only particular fields.

Display the result

<?php if (!$activities): ?>
  <p>No activities are available.</p>
<?php else: ?>
  <table>
    <thead>
      <tr>
        <th scope="col">Activity</th>
        <th scope="col">Location</th>
        <th scope="col">Capacity</th>
      </tr>
    </thead>
    <tbody>
      <?php foreach ($activities as $activity): ?>
        <tr>
          <td><?= htmlspecialchars($activity["activity_name"]) ?></td>
          <td><?= htmlspecialchars($activity["location"]) ?></td>
          <td><?= (int) $activity["capacity"] ?></td>
        </tr>
      <?php endforeach; ?>
    </tbody>
  </table>
<?php endif; ?>

The condition handles an empty dataset. The loop creates one row per record. Table headers support interpretation and accessibility.

Check


Revision #1
Created 2026-08-18 23:33:40 UTC by Mr Napper
Updated 2026-08-18 23:33:43 UTC by Mr Napper