MySQL

How to Fetch Data from Database in PHP and Display in HTML Table using PDO

In this tutorial, we are going to see how to fetch data from a database in PHP and display it in HTML table using PDO. If you are a “newbie” you should know how to connect to a MySQL database before using the code below. You cannot select data from a database if you are not connected to it.
 

How to fetch data from a database in PHP and display it in HTML table using PDO

In the example below, we query all the data from “Users” table, you can use the following script:
 

<?php
	$host = 'localhost';
	$dbname = 'test';
	$username = 'root';
	$password = '';
		
	$dsn = "mysql:host=$host;dbname=$dbname"; 
	// get all users
	$sql = "SELECT * FROM Users";
	 
	try{
	 $pdo = new PDO($dsn, $username, $password);
	 $stmt = $pdo->query($sql);
	 
	 if($stmt === false){
		die("Error");
	 }
	 
	}catch (PDOException $e){
		echo $e->getMessage();
	}
?>
<!DOCTYPE html>
<html>
<head>Display all users</head>
<body>
 <h1>Users list</h1>
 <table>
   <thead>
     <tr>
       <th>ID</th>
       <th>Name</th>
     </tr>
   </thead>
   <tbody>
     <?php while($row = $stmt->fetch(PDO::FETCH_ASSOC)) : ?>
     <tr>
       <td><?php echo htmlspecialchars($row['id']); ?></td>
       <td><?php echo htmlspecialchars($row['name']); ?></td>
     </tr>
     <?php endwhile; ?>
   </tbody>
 </table>
</body>
</html>

Output:
 

mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *