How to make pagination in php mysql
By Ved Prakash N |
Sep 24, 2023 |
PHP
How to Create Pagination in PHP and MYSQL
In this post, we will be learning about how to make dynamic pagination in php mysql. This code is very simple to learn and integrate into the project. In this pagination we show 10 records per page (paginate), if you want to change the per page paginate value in the code.
View:
The below code is for creating dynamic pagination in php mysql where we show 10 record per page (paginate):
<?php
$conn = mysqli_connect('localhost','root','','fundacodester');
if(!$conn){
die('Connection Failed'. mysqli_connect_error());
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>How to make pagination in php mysql</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" >
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="text-center my-4">
<h1>How to make pagination in php mysql</h1>
</div>
<?php
$countryQuery = mysqli_query($conn, "SELECT * FROM countries");
$totalCountry = mysqli_num_rows($countryQuery); //counting total number of rows
if(!isset ($_GET['page'])){
$page_number = 1;
}else{
if(!is_numeric($_GET['page'])){
$page_number = 1;
}else{
$page_number = $_GET['page'];
}
}
$limitPerPage = 10;
$startFrom = ($page_number-1) * $limitPerPage;
$countries = mysqli_query($conn, "SELECT * FROM countries LIMIT " . $startFrom . ',' . $limitPerPage);
$total_pages = ceil($totalCountry / $limitPerPage);
?>
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<?php foreach($countries as $country) : ?>
<tr>
<td><?= $country['id']; ?></td>
<td><?= $country['country']; ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<div class="float-end">
<nav aria-label="Page navigation example">
<ul class="pagination">
<?php for($pagination = 1; $pagination <= $total_pages; $pagination++) : ?>
<li class="page-item
<?= isset($_GET['page']) ? ($_GET['page'] == $pagination ? 'active':'') : ($pagination == 1 ? 'active':''); ?>
">
<a class="page-link" href="index.php?page=<?= $pagination; ?>">
<?= $pagination; ?>
</a>
</li>
<?php endfor; ?>
</ul>
</nav>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
I hope this helps you.