Home About Contact Privacy Terms Disclaimer
TECHAntena
Last Updated On: August 12, 2018
Editor: Adeeb C

How to Create Pagination in PHP – Next Page & Previous Page

Category: PHP
Tags

Here I’m going to explain you, ho to create the pagination in PHP. I’m giving you the example to create the ‘next page and previous page’ pagination along with the numbered pagination.

Create Pagination in PHP – Next Page & Previous Page

Here I provide an example program to use the pagination in PHP. In this example, the variable pid is used for the pagination. This variable stores the page number.

Program Code:

<?php
    if (isset($_GET["pid"])) { 
         $q = $_GET["pid"]; 
       } 
    else { 
         $pid=1; 
     };
   $results_per_page=10;
   $starting_from = ($pid-1) * $results_per_page;
$sql = "SELECT * FROM table_name ORDER BY id ASC LIMIT $start_from, ".$results_per_page;
?>

Here the result_per_page indicates how many items you need to display in a single page.

Now place the below code where you need to implement the pagination.

<?php
$sql = "SELECT COUNT(id) AS total FROM table_name";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$total_pages = ceil($row["total"] / $results_per_page);
if($pid!==1){
echo ("<a class=\"nav\" href=\"page.php?pid=".($pid-1)."\">Previous Page</a>"); 
}
for ($i=1; $i<=$total_pages; $i++) { 
echo "<a href='page.php?pid=".$i."' style=\"padding:5px; border:1px solid;\"";
if ($i==$pid) echo " class='active_page'";
echo ">".$i."</a> "; 
};
if($pid<$total_pages){
echo ("<a class=\"nav\" href=\"page.php?pid=".($pid+1)."\">Next Page</a>"); 
}

I hope this example might help you. If you have any doubts please comment below.