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

[vc_row][vc_column][vc_column_text]Want to learn, How to fetch data from the database in PHP and display 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>
<html>
<head>
<title>Table with database</title>
<style>
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}
</style>
</head>
<body>
<table>
<tr>
<th>Id</th>
<th>Username</th>
<th>Password</th>
</tr>
<?php
$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"; }
$conn->close();
?>
</table>
</body>
</html>

The output of the above code

How to fetch data from the database in PHP and display in the HTML tableExplaining 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 HTML table using PHP and MySQL database.

You may also like to:

5 1 vote
Article Rating
Subscribe
Notify of
5 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Fuse Gamer
2 years ago

thanks it works

tanmusique
tanmusique
2 years ago

how to work with sqlite

trackback
1 year ago

[…] I’m on a project where I’ve to show 4 tables on the same page. I found this : https://www.codeandcourse.com/how-to-display-data-from-mysql-database-into-html-table-using-php/. […]

Diesel
Diesel
1 year ago

yes runs good thx

Parker Shannon
Parker Shannon
1 year ago

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

echo “

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