49
1
0
How To Display MySQL Data in HTML Table with PHP

How To Display MySQL Data in HTML Table with PHP

Published on July 3, 2025 by OBSCountdown Editorial

Display MySQL Data in HTML Table with PHP

Learn how to fetch rows from a MySQL database and display them in a well-formatted HTML table using PDO in PHP.

๐Ÿ“Œ Why Display Data in a Table?

Displaying database content in an HTML table is essential for dashboards, reports, admin panels, and user interfaces. It's the most effective way to visualize tabular data.

๐Ÿ”Œ Connect to the Database

<?php
$pdo = new PDO("mysql:host=localhost;dbname=demo", "user", "pass");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>

๐Ÿ“„ Fetch and Display Data

<?php
$stmt = $pdo->query("SELECT id, username, email FROM users");
$rows = $stmt->fetchAll();
?>

<table border="1" cellpadding="8" cellspacing="0">
  <thead>
    <tr>
      <th>ID</th>
      <th>Username</th>
      <th>Email</th>
    </tr>
  </thead>
  <tbody>
    <?php foreach ($rows as $row): ?>
      <tr>
        <td><?= htmlspecialchars($row['id']) ?></td>
        <td><?= htmlspecialchars($row['username']) ?></td>
        <td><?= htmlspecialchars($row['email']) ?></td>
      </tr>
    <?php endforeach; ?>
  </tbody>
</table>

โœ… Best Practices

  • Always use htmlspecialchars() when outputting user data
  • Use CSS to improve table appearance
  • Consider paginating large datasets

๐Ÿงพ Summary

Displaying MySQL data in an HTML table is simple with PDO and PHP. With secure coding practices and a bit of styling, you can make your tables look professional and easy to use.

Comments (0)

No comments yet. Be the first to comment!

Leave a Comment
Replying to someone's comment. Cancel
49
1
0
Join Our OBS Community

Loading...

Join Now