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

March 5, 2019

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:

    if (isset($_GET["pid"])) { 
         $q = $_GET["pid"]; 

    else { 

   $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.


$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);

 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> "; 

 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.

About Author
Adeeb C (233 Articles)

Adeeb C is a Web Designer, Web Application Developer, Android App Developer, WordPress Developer, Professional Blogger. He has 5 years of experience in WordPress, Web Developing, Professional Blogging, and 2 years of experience in Android App Developing.