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.