Dynamic Pagination in PHP with Next and Previous

In this tutorial, I will learn you How to create dynamic pagination in PHP. Even I have shared the best & general source code within a custom function. This function will help you to create multiple paginations in multiple web pages by writing the given code at once.  This code is very simple to learn and integrate into the project.

Before Starting Coding, You should know the following basic information for your better understanding.

Pagination in PHP?

Pagination is the group of multiple web pages. It divides the large records into a limited number of records and displays them into more than one web page. Even It can quickly lead the records one by one page.

Pagination is also commonly used features in almost various web applications. Because this feature makes it very simple to view the large records. Even you can see it on my blog Home page.

Why Need PHP Pagination?

Most of the cases, Developers have to display a large number of records on the web page. But they can’t display those records on a single web page. Because Those records will take much time to load. Even those may fail to load together. So, It is not a good way to display all the records at once in only one page.

Hence, Developers need PHP pagination to remove the loading issue and easily display the records in a proper way.

Pagination Formula in PHP

This is the general formula to use for creating pagination in PHP.

You can use the following formula to find the total number of pagination pages.

$totalPages = ceil($totalRecords / $totalRecordsPerPage);

You can use the following formula to find the total number of previous records. It helps to display the next record by using the MySQL limit.

$totalPreviousRecords = ($currentPage-1) * $totalRecordsPerPage;

Example

Suppose that you have a total of 50 records are saved in the database. you have to display 5 records per page. Now you can calculate the total number of pages, the total number of previous records & the next 5 records using the above formula. (Suppose current page number is 3).

//From above example, We get
  $totalRecords=50;
  $totalRecordsPerPage=5;
  $currentPage= 3;

//using formula
  $totalPages = ceil($totalRecords / $totalRecordsPerPage);
  $totalPages= ceil(50/5); // output 10

// Hence, Total of 10 pagination pages will be created

// Now,using formula
   $totalPreviousRecords = ($currentPage-1) * $totalRecordsPerPage;
   $totalPreviousRecords = (3-1)*5; // output 10

// Hence, total number of previous recods is 10
// In this way, you can get next 5 records using the following query
   SELECT * From tableName limit $totalPreviousRecords, $totalRecordsPerPage;

// So, This query will be like 
   SELECT * From tableName limit 10, 5;

// Hence, the above query will select next 5 records except previous 10 records

How to create pagination in PHP and MYSQL

Here, you will learn to create pagination with a blog post example. This example will load 5 records at once. But you need not worry, I have created the general code to implement it. So, you can easily update it according to your requirement.
pagination in php

Basic Configuration

Before going to the next step, you should configure the following basic things

  • Create the following folder structure
myproject/
   |__database.php
   |__pagination-page.php
   |__pagination-script.php
   |

 

  • Create a MySQL Database & table

I have created codingstatus database & blogs table. You can create it according to your project requirement.

  • Insert Records into MySQL Table

I will create pagination to insert 65 records in a blogs. You can insert it according to your project requirement.

Read Also  How to Insert Data Using Ajax in PHP and MySQL

  • Now write the script of the next steps in pagination.php. all the script is written within user-defined functions. do the following script in it.
    • Write  require('database.php')  to connect MySQL database.
    • Initialize connection variable by using $db=$connection

1. Connect PHP to MYSQL Database

Write the following Query to connect PHP to MySQL database.

$hostname     = "localhost"; // Enter your hostname
$username     = "root"; // enter your table username
$password     = ""; // enter your table password
$databasename = "codingstatus.com"; // enter your database name

// Create connection
$connection = mysqli_connect($hostname, $username, $password,$databasename);
// Check connection
if (!$connection) {
    die("Unable to Connect database: " . mysqli_connect_error());
}

2. Get Current Page Number

Write the following PHP script to get the current page number.

// current page number
function current_page(){

    if (isset($_GET['page']) && $_GET['page']!="") {
      $currentPage = validate($_GET['page']);
    } else {
        $currentPage = 1;
    }
return $currentPage;
}

page is the query string object of pagination link. you can get current page number using $_Get['page']. if it does not have any value, it will be equal to 1.

3. Validate Current Page Number

$_Get['page'] is passed in validate() custom function to protect from hackers. this custom function is declared using the following script.

// validate current page number
function validate($value) {
  $value = trim($value);
  $value = stripslashes($value);
  $value = htmlspecialchars($value);
  return $value;
}

4. Fetch Pagination Records

Write the following PHP script to create pagination records.

// fetching padination data
function pagination_records($totalRecordsPerPage,$tableName){
   global $db;
   $currentPage=current_page();
   $totalPreviousRecords = ($currentPage-1) * $totalRecordsPerPage;

  $query = $db->prepare("SELECT * FROM ".$tableName." LIMIT ?, ?");
  $query->bind_param('ii',$totalPreviousRecords,$totalRecordsPerPage); 
  $query->execute();
  $result=$query->get_result();

  if($result->num_rows>0){
    $row= $result->fetch_all(MYSQLI_ASSOC);
    return $row;       
  }else{
    return $row=[];
  }
}

You can call the above function and pass the total number of records per page & table name. This the general function. you can fetch any table records by passing the table name as a parameter.

Suppose you have to fetch total 5 records per page from blogs. then you can call it as

$totalRecordsPerPage=5;
$tableName= 'blogs';
$paginationRecords=pagination_records($totalRecordsPerPage,$tableName);
print_r($paginationRecords);

5. Create Serial Number of Pagination Records

Write the following PHP script to create a serial number of pagination records

// serial number of pagination content
function pagination_records_counter($totalRecordsPerPage){
 
    $currentPage=current_page();

    $totalPreviousRecords=($currentPage-1)*$totalRecordsPerPage;
    $dataCounter=$totalPreviousRecords + 1;
    
    return $dataCounter;

}

You can call the above function where you want to display pagination records. Even you have to pass the total number of records per page.

If you have to display a total of 5 records per page, call it as

$totalRecordsPerPage=3
pagination_records_counter($totalRecordsPerPage);

 

6. Create the Previous Pagination in PHP

Write the following script to create the previous pagination page.

// back to previous page
function previous_page(){
 $currentPage=current_page();
 $previousPage = $currentPage - 1;
 if($currentPage > 1){
   $previous="<a href='?page=".$previousPage."'>Previous</a>";
   return $previous; 
}}

7. Create the Next Pagination in PHP

Write the following script to create the next pagination page.

// go to next page
function next_page($totalPages){

$currentPage=current_page();
$nextPage = $currentPage + 1;
if($currentPage < $totalPages) {
$next="<a href='?page=".$nextPage."'
>Next</a>";
return $next;

}}

8. Create Pagination Serial Numbers

Write the following script to create serial numbers of pagination link

// diplaying total pagination numbers
function pagination_numbers($totalPages){
    $currentPage=current_page();
    $adjacents = "2";
    $second_last = $totalPages - 1; // total pages minus 1

    $pagelink='';
    if ($totalPages <= 5){   
     for ($counter = 1; $counter <= $totalPages; $counter++){
      if ($counter == $currentPage) {
           $pagelink.= "<a class='active'>".$counter."</a>"; 
      }else{
          $pagelink.= "<a href='?page=".$counter."'>".$counter."</a>";
      }
     }
    }elseif ($totalPages > 5){
      if($currentPage <= 4) { 
        for ($counter = 1; $counter < 8; $counter++){ 
        if ($counter == $currentPage) {
        $pagelink.= "<a class='active' href='?page=".$counter."'>".$counter."</a>";
        }else{
           $pagelink.= "<a href='?page=".$counter."'>".$counter."</a>";
        }
      }
  $pagelink.= "<a>...</a>";
  $pagelink.= "<a href='?page=".$second_last."'>".$second_last."</a>";
  $pagelink.= "<a href='?page=".$totalPages."'>".$totalPages."</a>";

  }elseif($currentPage > 4 && $currentPage < $totalPages - 4) { 
   $pagelink.= "<a href='?=1'>1</a>";
   $pagelink.= "<a href='?page=2'>2</a>";
   $pagelink.= "<a>...</a>";
   for (
     $counter = $currentPage - $adjacents;
     $counter <= $currentPage + $adjacents;
     $counter++
     ) { 
     if ($counter == $currentPage) {
        $pagelink.= "<a class='active'>".$counter."</a>"; 
     }else{
        $pagelink.= "<a href='?page=".$counter."'>".$counter."</a>";
     }                  
   }
  $pagelink.= "<a>...</a>";
  $pagelink.= "<a href='?page=".$second_last."'>".$second_last."</a>";
  $pagelink.= "<a href='?page=".$totalPages."'>".$totalPages."</a>";
  }else {
  $pagelink.= "<a href='?page=1'>1</a>";
  $pagelink.= "<a href='?page=2'>2</a>";
  $pagelink.= "<a>...</a>";
  for (
     $counter = $totalPages - 6;
     $counter <= $totalPages;
     $counter++
   ) {
     if ($counter == $currentPage) {
       $pagelink.= "<a class='active'>".$counter."</a>"; 
     }else{
       $pagelink.= "<a href='?page=".$counter."'>".$counter."</a>";
      }                   
  }
 }
}
return $pagelink;
}

9. Create Pagination in PHP

Write the following script to create complete pagination.

// final script to create pagination
function pagination($totalRecordsPerPage,$tableName){
  $currentPage=current_page();
  global $db; 

  // calculation
  $query ="SELECT * FROM ".$tableName;
  $result=$db->query($query);

  $totalRecords=$result->num_rows;
  $totalPages = ceil($totalRecords / $totalRecordsPerPage);

  $pagination='';
  $pagination.=previous_page();
  $pagination.=pagination_numbers($totalPages);
  $pagination.=next_page($totalPages);

  return $pagination;
}

This is the final & general pagination script. you can create multiple paginations on one or more pages. Only you have to pass a total number of records per page & table name.

Suppose that you want to fetch a total of 5 records per page from blogs table

$totalRecordsPerPage= 5;
$tableName= 'blogs';
$pagination = pagination($totalRecordsPerPage,$tableName);
echo $pagination;

10. Display Pagination & its records

Write the following script in file pagination-page.php to display pagination & its records.

<?php
require_once('pagination-script2.php');
 $totalRecordsPerPage=5;
 $tableName='blogs';
 $paginationData=pagination_records($totalRecordsPerPage,$tableName);
 $sn=pagination_records_counter($totalRecordsPerPage);
 $pagination=pagination($totalRecordsPerPage,$tableName);

?>
<!--====pagination content  start====-->
<div class="pagination-content">
<?php

foreach ($paginationData as $data) {

   ?>
   <h1><?php echo $sn.". ".$data['title'];?></h1>
   <p><?php echo $data['description'];?></p>

   <?php 
$sn++;}
?>
</div>
<!--====pagination content end====-->
<br><br>
<!--====pagination section start====-->
<div class="pagination">
<?php
echo $pagination;
?>
</div>
<!--====pagination section end====-->

In the above script, you will load a total of 5 records per page from blogs table. you can use it to create another pagination for another table records.

11. Design Pagination Using CSS

Write the following CSS code to design pagination.

.pagination-content{
   width:60%;
   text-align: justify;
   padding:20px;
}
.pagination{
   padding:20px;
}
.pagination a.active{
   background: #f77404;
   color: white;
}
.pagination a{
    text-decoration: none;
    padding: 10px 15px;
    box-shadow: 0px 0px 15px #0000001c;
    background: white;
    margin: 3px;
    color: #1f1e1e;
}

 

PHP Pagination Function

I have created custom functions using PHP. It will work to create different types of pagination in PHP.So, you can create other multiple records & multiple paginations of other tables.

For creating more than one pagination, you need not change anything in its main script. just pass the total number of records per page & table name as a parameter to the following function.

pagination_records($totalRecordsPerPage,$tableName);
pagination($totalRecordsPerPage,$tableName);

Suppose that you have to show & create the following records & pagination respectively

  • Show 5 records per page from users table
$totalRecordsPerPage=5;
$tableName='users'
$paginationRecords=pagination_records($totalRecordsPerPage,$tableName); 

$pagination=pagination($totalRecordsPerPage,$tableName);

// display pagination records
 foreach($paginationRecords as $data){

// here you will echo multiple column data  using $data['column_name'] syntax
}

// display pagination
echo $pagination;

 

  • Show 7 records per page from the students table
$totalRecordsPerPage=;
$tableName='students'
$paginationRecords=pagination_records($totalRecordsPerPage,$tableName); 
$pagination=pagination($totalRecordsPerPage,$tableName);
// display pagination records
 foreach($paginationRecords as $data){
// here you will echo multiple column data  using $data['column_name'] syntax
}
// display pagination
echo $pagination;
  • show 10 records per page from the employees table.
$totalRecordsPerPage=10;
$tableName='users'
$paginationRecords=pagination_records($totalRecordsPerPage,$tableName); 
$pagination=pagination($totalRecordsPerPage,$tableName);
// display pagination records
 foreach($paginationRecords as $data){
// here you will echo multiple column data  using $data['column_name'] syntax
}
// display pagination
echo $pagination;

 

Use Complete Code to Create  Pagination in php

You can use the following complete scripts to create pagination & load records in your project.

File Name: pagination-script.php

<?php
require('database.php');
$db=$connection; // enter your connection variable
// current page number
function current_page(){
if (isset($_GET['page']) && $_GET['page']!="") {
$currentPage = validate($_GET['page']);
} else {
$currentPage = 1;
}
return $currentPage;
}
// validate current page number
function validate($value) {
$value = trim($value);
$value = stripslashes($value);
$value = htmlspecialchars($value);
return $value;
}
// fetching padination data
function pagination_records($totalRecordsPerPage,$tableName){
global $db;
$currentPage=current_page();
$totalPreviousRecords = ($currentPage-1) * $totalRecordsPerPage; 
$query = $db->prepare("SELECT * FROM ".$tableName." LIMIT ?, ?");
$query->bind_param('ii',$totalPreviousRecords,$totalRecordsPerPage); 
$query->execute();
$result=$query->get_result();
if($result->num_rows>0){
$row= $result->fetch_all(MYSQLI_ASSOC);
return $row;  
}else{
return $row=[];
}
}
// serial number of pagination content
function pagination_records_counter($totalRecordsPerPage){
$currentPage=current_page();
$totalPreviousRecords=($currentPage-1)*$totalRecordsPerPage;
$dataCounter=$totalPreviousRecords + 1;
return $dataCounter;
}
// back to previous page
function previous_page(){
$currentPage=current_page();
$previousPage = $currentPage - 1;
if($currentPage > 1){
$previous="<a href='?page=".$previousPage."'>Previous</a>";
return $previous;
}  
}
// go to next page
function next_page($totalPages){
$currentPage=current_page();
$nextPage = $currentPage + 1;
if($currentPage < $totalPages) {
$next="<a href='?page=".$nextPage."'
>Next</a>";
return $next;
}}
// diplaying total pagination numbers
function pagination_numbers($totalPages){
$currentPage=current_page();
$adjacents = "2";
$second_last = $totalPages - 1; // total pages minus 1
$pagelink='';
if ($totalPages <= 5){   
for ($counter = 1; $counter <= $totalPages; $counter++){
if ($counter == $currentPage) {
$pagelink.= "<a class='active'>".$counter."</a>"; 
}else{
$pagelink.= "<a href='?page=".$counter."'>".$counter."</a>";
}
}
}elseif ($totalPages > 5){
if($currentPage <= 4) { 
for ($counter = 1; $counter < 8; $counter++){ 
if ($counter == $currentPage) {
$pagelink.= "<a class='active' href='?page=".$counter."'>".$counter."</a>";
}else{
$pagelink.= "<a href='?page=".$counter."'>".$counter."</a>";
}
}
$pagelink.= "<a>...</a>";
$pagelink.= "<a href='?page=".$second_last."'>".$second_last."</a>";
$pagelink.= "<a href='?page=".$totalPages."'>".$totalPages."</a>";
}elseif($currentPage > 4 && $currentPage < $totalPages - 4) { 
$pagelink.= "<a href='?=1'>1</a>";
$pagelink.= "<a href='?page=2'>2</a>";
$pagelink.= "<a>...</a>";
for (
$counter = $currentPage - $adjacents;
$counter <= $currentPage + $adjacents;
$counter++
) { 
if ($counter == $currentPage) {
$pagelink.= "<a class='active'>".$counter."</a>"; 
}else{
$pagelink.= "<a href='?page=".$counter."'>".$counter."</a>";
}                  
}
$pagelink.= "<a>...</a>";
$pagelink.= "<a href='?page=".$second_last."'>".$second_last."</a>";
$pagelink.= "<a href='?page=".$totalPages."'>".$totalPages."</a>";
}else {
$pagelink.= "<a href='?page=1'>1</a>";
$pagelink.= "<a href='?page=2'>2</a>";
$pagelink.= "<a>...</a>";
for (
$counter = $totalPages - 6;
$counter <= $totalPages;
$counter++
) {
if ($counter == $currentPage) {
$pagelink.= "<a class='active'>".$counter."</a>"; 
}else{
$pagelink.= "<a href='?page=".$counter."'>".$counter."</a>";
}                   
}}}
return $pagelink;
}
// final script to create pagination
function pagination($totalRecordsPerPage,$tableName){
$currentPage=current_page();
global $db; 
$query ="SELECT * FROM ".$tableName;
$result=$db->query($query);
$totalRecords=$result->num_rows;
$totalPages = ceil($totalRecords / $totalRecordsPerPage);
$pagination='';
$pagination.=previous_page();
$pagination.=pagination_numbers($totalPages);
$pagination.=next_page($totalPages);
return $pagination;
}
?>

File Name: pagination-page.php

<!DOCTYPE html>
<html lang="en">
<head>
<title>Pagination in PHP</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style type="text/css">
.pagination-content{
width:60%;
text-align: justify;
padding:20px;
}
.pagination{
padding:20px;
}
.pagination a.active{
background: #f77404;
color: white;
}  
.pagination a{
text-decoration: none;
padding: 10px 15px;
box-shadow: 0px 0px 15px #0000001c;
background: white;
margin: 3px;
color: #1f1e1e;
}
</style>
</head>
<body>
<?php
require_once('pagination-script2.php');
$totalRecordsPerPage=5;
$tableName='blogs';
$paginationData=pagination_records($totalRecordsPerPage,$tableName);
$sn=pagination_records_counter($totalRecordsPerPage);
$pagination=pagination($totalRecordsPerPage,$tableName);
?>
<!--====pagination content  start====-->
<div class="pagination-content">
<?php
foreach ($paginationData as $data) {
?>
<h1><?php echo $sn.". ".$data['title'];?></h1>
<p><?php echo $data['description'];?></p>
<?php 
$sn++;}
?>
</div>
<!--====pagination content end====-->
<br><br>
<!--====pagination section start====-->
<div class="pagination">
<?php
echo $pagination;
?>
</div>
<!--====pagination section end====-->
<br><br><br>
</body>
</html>

 

Suggestion

You have learned the best pagination in PHP with the above script. Now, you are able to create another pagination like Blog Pagination, Table pagination & Product Pagination so on.

I hope you like this tutorial. Even it is useful for you. So, Don’t forget to share with friends those who want to learn it.

If you have any queries, you can ask me through the below comment box. I will also share more coding tutorials. So you should continue to visit my blog for becoming expert in the coding field.

 

Categories PHP

Leave a Comment