How to Fetch/Retrieve data from database in PHP MySQL
By Super Admin |
May 31, 2021 |
PHP
How to Fetch/Retrieve data from database in PHP MySQL
In this post, you will be learning how to retrieve data from mysql table in php, We will be using Bootstrap 5 version to design the user interface.
So, Lets get started to fetch data from DB in html table using php mysql:
Step 1: Create a mysql table in database named student:
CREATE TABLE `student` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`stud_name` varchar(191) NOT NULL,
`stud_class` varchar(100) NOT NULL,
`stud_phone` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
);
After successful creation of table, Insert / Add few records in this student table to fetch the data.
Step 2: Create a file named index.php and paste the below code as follows:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Funda of Web IT</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="row justify-content-center">
<div class="col-md-12">
<div class="card mt-5">
<div class="card-header">
<h4>How to Fetch Data from Database in PHP MySQL</h4>
</div>
<div class="card-body">
<table class="table table-bordered">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Class</th>
<th>Phone No</th>
</tr>
</thead>
<tbody>
<?php
$con = mysqli_connect("localhost","root","","database_name");
$query = "SELECT * FROM student";
$query_run = mysqli_query($con, $query);
if(mysqli_num_rows($query_run) > 0)
{
foreach($query_run as $row)
{
?>
<tr>
<td><?= $row['id']; ?></td>
<td><?= $row['stud_name']; ?></td>
<td><?= $row['stud_class']; ?></td>
<td><?= $row['stud_phone']; ?></td>
</tr>
<?php
}
}
else
{
?>
<tr>
<td colspan="4">No Record Found</td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
Now, you can run and check the output
Thanks for reading...