How To Display MySQL Data in HTML Table with PHP

Fetch and display database rows in a clean HTML table using PHP.

2 min read •
250 1 0

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. Cancel