How to fetch data from database using pdo in php
Fetch data from database using pdo in php
In this tutorial, you will be learning how to get data from database using PDO in PHP MySQL.
We are going to use Bootstrap 5 to design the html table.
Step 1: Create database connection:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "phptutorials";
try {
$conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // set the PDO error mode to exception
// echo "Connected Successfully";
} catch(PDOException $e) {
echo "Connection Failed" .$e->getMessage();
}
?>
Step 2: Create a file named index.php to fetch data:
<?php
include('dbcon.php');
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
<title>Fetch data from database using pdo in php</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-12 mt-4">
<div class="card">
<div class="card-header">
<h3>Fetch data from database using pdo in php </h3>
</div>
<div class="card-body">
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>ID</th>
<th>FullName</th>
<th>Email</th>
<th>Phone</th>
<th>Course</th>
</tr>
</thead>
<tbody>
<?php
$query = "SELECT * FROM students";
$statement = $conn->prepare($query);
$statement->execute();
$statement->setFetchMode(PDO::FETCH_OBJ); //PDO::FETCH_ASSOC
$result = $statement->fetchAll();
if($result)
{
foreach($result as $row)
{
?>
<tr>
<td><?= $row->id; ?></td>
<td><?= $row->fullname; ?></td>
<td><?= $row->email; ?></td>
<td><?= $row->phone; ?></td>
<td><?= $row->course; ?></td>
</tr>
<?php
}
}
else
{
?>
<tr>
<td colspan="5">No Record Found</td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
Thank you.