How to Display MySQL Data in HTML Table Using JavaScript: A 2026 Guide
Learn how to dynamically display MySQL database entries in an HTML table using JavaScript and PHP. This guide covers setup, data fetching, and populating the table.
How to Display MySQL Data in HTML Table Using JavaScript: A 2026 Guide
Displaying MySQL database entries in an HTML table using JavaScript is a common task for web developers. It allows you to present data dynamically fetched from a server to the end-user in a structured and readable format. This tutorial will guide you through the process of fetching data from a MySQL database and displaying it in an HTML table using JavaScript and AJAX. Whether you're building an admin dashboard or a simple data display page, mastering this skill is essential.
Key Takeaways
- Learn how to fetch MySQL data using AJAX and PHP.
- Understand how to dynamically populate an HTML table with JavaScript.
- Discover common issues and their troubleshooting methods.
- Prerequisites include basic knowledge of HTML, JavaScript, and PHP.
- Step-by-step guide to ensure correct data display.
Prerequisites
Before diving into the code, ensure you have the following:
- Basic understanding of HTML, CSS, and JavaScript.
- Knowledge of PHP and MySQL.
- A working development environment with a web server (e.g., XAMPP, WAMP).
- Access to a MySQL database with sample data.
Step 1: Set Up Your Database
First, ensure you have a MySQL database set up with the relevant data. For this tutorial, let's assume you have a database named my_database with a table called accounts. Here is a sample structure:
CREATE TABLE accounts (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50),
email VARCHAR(100),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);Populate the table with some sample data:
INSERT INTO accounts (username, email) VALUES ('user1', 'user1@example.com'), ('user2', 'user2@example.com');Step 2: Create the Backend PHP Script
Next, create a PHP script that will handle the database query and return the data in JSON format. Save this script as account_list.php:
<?php
// Establish database connection
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "my_database";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, username, email, created_at FROM accounts";
$result = $conn->query($sql);
$accounts = [];
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$accounts[] = $row;
}
}
echo json_encode($accounts);
$conn->close();
?>Step 3: Set Up the HTML Structure
Create an HTML file where you will display the data. Include jQuery for AJAX functionality:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Display MySQL Data</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
table { width: 100%; border-collapse: collapse; }
th, td { border: 1px solid #ddd; padding: 8px; }
th { background-color: #f2f2f2; }
</style>
</head>
<body>
<h1>Account List</h1>
<table id="accountTable">
<thead>
<tr>
<th>ID</th>
<th>Username</th>
<th>Email</th>
<th>Created At</th>
</tr>
</thead>
<tbody>
<!-- Data will be injected here -->
</tbody>
</table>
</body>
</html>Step 4: Fetch Data and Populate the Table With JavaScript
Now, write the JavaScript to fetch data from the server and populate the table. Include this script in your HTML file:
$(document).ready(function() {
loadAccountList();
function loadAccountList() {
$.ajax({
url: "account_list.php",
type: "GET",
dataType: "json",
success: function(data) {
var tableBody = "";
data.forEach(function(account) {
tableBody += "<tr>" +
"<td>" + account.id + "</td>" +
"<td>" + account.username + "</td>" +
"<td>" + account.email + "</td>" +
"<td>" + account.created_at + "</td>" +
"</tr>";
});
$('#accountTable tbody').html(tableBody);
},
error: function(xhr, status, error) {
console.error("Error fetching data: ", error);
}
});
}
});Common Errors/Troubleshooting
Here are some common issues you might encounter and how to troubleshoot them:
- No Data Displayed: Ensure your PHP script is correctly querying the database and returning JSON. Check your browser's console for AJAX errors.
- Incorrect Data Formatting: Verify that JSON data matches your table structure. Use
console.log()to inspect data. - AJAX Request Fails: Check your server's error logs for PHP errors and ensure the correct URL path is set.
Frequently Asked Questions
Why is my table not displaying any data?
Ensure the AJAX request is successful and that the PHP script returns correct JSON data.
How can I style my HTML table?
Use CSS to style your table. You can apply styles directly in the HTML file or in an external stylesheet.
Can I use fetch API instead of jQuery?
Yes, you can use the Fetch API to perform AJAX requests. It is a modern alternative to jQuery's AJAX method.
Frequently Asked Questions
Why is my table not displaying any data?
Ensure the AJAX request is successful and that the PHP script returns correct JSON data.
How can I style my HTML table?
Use CSS to style your table. You can apply styles directly in the HTML file or in an external stylesheet.
Can I use fetch API instead of jQuery?
Yes, you can use the Fetch API to perform AJAX requests. It is a modern alternative to jQuery's AJAX method.