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

Back to Posts
How to fetch data from the database in PHP and display in the HTML table

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 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.

Live Demo Here

You may also like to:

Share this post

Back to Posts