👋 Hey there, PHP developer! If you’re just getting started with PHP and MySQL, one of the first things you’ll likely need to do is display data from your database in a clean HTML table. Whether you’re building a product list, employee directory, or blog post dashboard, learning displaying database records in a PHP HTML table is essential.
In this easy-to-follow guide, you’ll learn everything from connecting to your database to outputting the records with clean formatting. We’ll use MySQLi (procedural) in our examples, but we’ll also show you how to enhance it for real-world scenarios.
Introduction
Displaying records from a database is a fundamental skill in PHP development. It allows you to present dynamic content, interact with users, and create data-driven applications. In this tutorial, we’ll walk you through everything you need to know to display database records in a PHP HTML table—without unnecessary complexity.
Why Displaying Data Matters
You don’t just store data in a database to forget about it. Most web apps are built around the ability to view, sort, and manage data. Whether it’s:
- Users checking their order history,
- Admins managing blog posts,
- HR viewing employee information—
The core is data display.
So learning to fetch and present this data effectively helps you build more interactive and useful web applications.
⚙️ Setting Up Your Environment
Before we write any code, make sure you have the following:
- A web server (like XAMPP, WAMP, or MAMP)
- A MySQL database created
- PHP installed (comes with XAMPP/WAMP)
- A code editor (VSCode, Sublime Text, etc.)
- A database table with some sample records
Create a MySQL Database and Table
First, create a sample database and table. You can use phpMyAdmin or MySQL CLI.
CREATE DATABASE sampledb;
USE sampledb;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
INSERT INTO users (name, email) VALUES
('John Doe', 'john@example.com'),
('Jane Smith', 'jane@example.com'),
('Alice Johnson', 'alice@example.com');
If you’re new to databases, check out our guide on How to Create MySQL Tables Using PHP.
🔌 Connecting to the Database
Create a file called db.php
and add the following code:
<?php
$host = "localhost";
$username = "root";
$password = "";
$database = "sampledb";
// Create connection
$conn = mysqli_connect($host, $username, $password, $database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
?>
✅ This creates a reusable database connection that you can include in multiple PHP files.
Writing the SQL Query
Now create a file display.php
and include the connection file:
<?php
include 'db.php';
$sql = "SELECT * FROM users";
$result = mysqli_query($conn, $sql);
?>
This simple SQL query selects all records from the users
table.
🖥️ Displaying the Data in an HTML Table
Below is the full code to display records in an HTML table using PHP:
<?php
include 'db.php';
$sql = "SELECT * FROM users";
$result = mysqli_query($conn, $sql);
?>
<!DOCTYPE html>
<html>
<head>
<title>User Records</title>
<style>
table {
width: 60%;
border-collapse: collapse;
margin: 20px auto;
}
th, td {
padding: 12px;
border: 1px solid #999;
text-align: center;
}
th {
background-color: #f2f2f2;
}
</style>
</head>
<body>
<h2 style="text-align:center;">User Records</h2>
<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
</tr>
<?php
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "<tr>
<td>{$row['id']}</td>
<td>{$row['name']}</td>
<td>{$row['email']}</td>
</tr>";
}
} else {
echo "<tr><td colspan='3'>No records found</td></tr>";
}
mysqli_close($conn);
?>
</table>
</body>
</html>
🚫 Handling No Results Gracefully
As seen above, the check:
if (mysqli_num_rows($result) > 0) {
// Display rows
} else {
echo "<tr><td colspan='3'>No records found</td></tr>";
}
This avoids breaking the table layout when there are no results. It’s a simple but professional touch.
🎨 Adding CSS for Better Presentation
You can improve the table’s readability by adding:
- Hover effects
- Alternate row colors
- Responsive layout
Here’s a small CSS improvement:
tr:nth-child(even) {
background-color: #f9f9f9;
}
tr:hover {
background-color: #e0f7fa;
}
Small UI changes like these enhance user experience.
❌ Common Mistakes to Avoid
- Forgetting to close the DB connection.
- Using unescaped user input (risk of SQL Injection).
- Mixing too much HTML with PHP (hard to read).
- Not checking for empty results.
- Using outdated
mysql_*
functions instead ofmysqli_*
orPDO
.
🎁 Bonus: Using PDO for More Flexibility (Optional)
PDO offers better error handling and supports multiple databases. Here’s how you can use it:
<?php
try {
$pdo = new PDO("mysql:host=localhost;dbname=sampledb", "root", "");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->query("SELECT * FROM users");
echo "<table border='1'>";
echo "<tr><th>ID</th><th>Name</th><th>Email</th></tr>";
while ($row = $stmt->fetch()) {
echo "<tr>
<td>{$row['id']}</td>
<td>{$row['name']}</td>
<td>{$row['email']}</td>
</tr>";
}
echo "</table>";
} catch (PDOException $e) {
die("Error: " . $e->getMessage());
}
?>
🌐 Real-World Use Case Example
Let’s say you’re building a simple admin panel for managing users. You could fetch and display users with additional options like Edit, Delete, or View Details buttons next to each row.
echo "<td><a href='edit.php?id={$row['id']}'>Edit</a></td>";
Adding this brings interactivity and real-world utility to your tables.
Tips to Improve Table Presentation
Make your data table more readable and professional:
- Use CSS for styling rows and columns
- Add pagination for large datasets
- Highlight rows on hover
- Make columns sortable with JavaScript libraries like DataTables
Learn more about DataTables – jQuery Plugin for Table Enhancements
Summary
Here’s a quick recap of what we covered:
✅ Created a MySQL database and table
✅ Connected PHP to MySQL
✅ Retrieved data using SQL
✅ Displayed data in a styled HTML table
✅ Explored PDO for secure access
✅ Shared tips on making your table responsive and interactive
Displaying data from a database in a PHP table is a foundational task in web development. With a few lines of code, you can create a dynamic and user-friendly interface that presents your data clearly and professionally.
🎯 Final Thoughts
This guide was designed to help beginners grasp the practical steps of working with databases and PHP to display useful information in a web-friendly format. Once you’ve mastered this, you can explore further by integrating JavaScript enhancements, advanced filters, and even export features like CSV and PDF.
Want to learn how to insert user-submitted form data into a database? Check out our Handling Form Submissions in PHP.
Got questions or suggestions? Drop them in the comments or send us a message—learning is better together!
Leave a Reply