How to Fetch Data from Database in PHP and display in HTML Table?

Want to learn, How to fetch data from the database in PHP and display it in the HTML table? Then keep reading and you will learn which query is used to fetch data from a database. Make a connection between the HTML Table and MySQL database using PHP. And also about some CSS to make HTML Table looks better.

But first, you can read How to send data from an HTML form to the MySQL database using Php.

Source Code

<!DOCTYPE html>
<title>Table with database</title>
table {
border-collapse: collapse;
width: 100%;
color: #588c7e;
font-family: monospace;
font-size: 25px;
text-align: left;
th {
background-color: #588c7e;
color: white;
tr:nth-child(even) {background-color: #f2f2f2}
$conn = mysqli_connect("localhost", "root", "", "company");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
$sql = "SELECT id, username, password FROM login";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["id"]. "</td><td>" . $row["username"] . "</td><td>"
. $row["password"]. "</td></tr>";
echo "</table>";
} else { echo "0 results"; }

The output of the above code

How to fetch data from the database in PHP and display in the HTML tableExplaining the above PHP code

Inline 29: Make a database connection so that we can fetch data from a database.

31, 32: If there is an error during a database connection then we display that error and exit the program. If there is no error then we continue our process.

34: SQL query to select data from a database.

35: Execute a SELECT query and store the result in a $result

36-40: If that result contains more than 0 rows then display that data in an HTML table

43, 44: If the result contains 0 rows then give a message “0 results” and close a database connection.

And this is how we fetch data from the database and display it on an HTML table using PHP and MySQL databases.

Conclusion: After you follow the above method, you display the data that you have stored in your database on your HTML table with the help of PHP, MySQL.

You may also like to:

4.2 5 votes
Article Rating
Notify of
Newest Most Voted
Inline Feedbacks
View all comments
Fuse Gamer
3 years ago

thanks it works

3 years ago

how to work with sqlite

3 years ago

[…] I’m on a project where I’ve to show 4 tables on the same page. I found this : […]

3 years ago

yes runs good thx

Parker Shannon
Parker Shannon
2 years ago

Nawaraj, do you know how to display “username” along with an associated hyperlink — “username” –?

echo “

” . $row[“id”]. “ ” . $row[“username”] . “ “