Contact me See Resume

10 easy steps to create simple pagination using PHP - nareshonline.com

10 easy steps to create simple pagination using PHP

Catagory : PHP and mySQLi Posted : November, 10, 2018
pagination in php by nareshonline.com

In this tutorial we will achieve pagination using PHP in 10 easy steps.  This is a simple pagination using PHP and mySQLi. Without using any plugin or Javascript and jQuery. PHP made pagination is very simple. In this tutorial we will follow 10 easy steps to create simple pagination using PHP for basic requirement of pagination. Like page links, Previous and Next button with auto hide and show as we need.

HTML Structure :

For just tutorial purpose we need only two Div Tags one for showing results and another for pagination control.

PHP Code :

For ease of understanding I have divided PHP code in steps :

  1. Database connection.
  2. Define how many records you want to display per page.
  3. Select data from Table.
  4. Determines total records in table.
  5. Calculate the total pages available.
  6. Observe on which page visitor is visiting.
  7. Setting for start and end record to display on page.
  8. Retrieve selected result on page.
  9. Close the database connection as we don’t require remain open any more.
  10. Making page links.
    • previous link appear when you are on page no. 2 or more than page no. 2 (optional)
    • page links
    • Next page link disappear when user visits on last page (optional).

Lets code to make simple pagination using PHP and mySQLi.

Step 1 : Database Connection

Here I am using Localhost and my database name is pagination.

$conn = mysqli_connect("localhost", "root", "", "pagination") or die("Connection failed: " . mysqli_connect_error());

Step 2 : Define how many records you want to display per page.

I want to fetch 5 records per page. You can change it as per your requirement according to your data.

$records_per_page = 5;

Step 3 : Select Data from table.

For demo purpose I have create a table name ‘data’ with two columns first is ‘ID’ and second is ‘Alphabets’ and inserted records.  Now we have to select data from table and run query.

// selecting data from table named 'data'
$sel = "SELECT * FROM data";
// run the query and get all data in a local variable called $result
$result = mysqli_query($conn, $sel);

Step 4 : Determines total records in table

Now we need to find how many records exist in our table by using mysqli_num_rows().

$total_records = mysqli_num_rows($result);

Step 5 : Calculate the total pages available

Now we have to calculate the total pages available in our data table. Which we can easily  get by dividing total records to records per page. For ease of doing we have already done it by creating local variable $total_records and $record_per_page.

$total_page = $total_records / $records_per_page;

As we know this result can be come in “.” (points) like 2.3 or 4.6. But our page cant display Like this. So we use here ceil() function make round off result. for example if we have 2.3 in total pages, the ceil() function will convert it in 3 or if we have 4.6 in total page the ceil() function convert it into 5.

So finally we use this code to get total page

$total_page = ceil($total_records / $records_per_page);

Step 6 : Observe on which page visitor is visiting.

We can loop though the links for page control.

for($page=1; $page<=$total_page;$page++){			
    echo '<a href="pagination.php?page='.$page.'"> ' . $page . ' </a>';
}

First of all we have to create a global variable using $_GET () method,  when user click on the particular link, this variable hold the page number value. So we can  easily achieve that which is page is currently visiting by user. By default page 1 is displayed. But user visited another page, we can check it by $_GET();

Note : We use the above code later in this tutorial. here I just show for making easy understand of code.

if(!isset($_GET['page'])){
  $page = 1;
} else {
  $page = $_GET['page'];
  }

Step 7 : Setting for start and end record to display on page.

Now will set LIMIT for mySQLi select query.

mySQLi  LIMIT its take two parameter first is OFFSET and second is range (first is optional). we provide  only one parameter it will show only first record to desire result .

Example

“SELECT * FROM data LIMIT 5”;

It will display first five records from data table.

On the other hand the OFFSET is use to display from particular records.

“SELECT * FROM data LIMIT 5, 5”;

It will display from sixth record to next five record on webpage (indexing starts from zero (0).

Setting for OFFSET

Suppose user clicked on page number 1, so we have to show the second next 5 records on page.

Lets calculate

$start = (1-1) * 5      // display 5 records per page

then $start will 0, so we have to display records from 0 to next 5.

if user clicked on page number 2 then

$start = (2-1)*5 = 5,  we have to display records from 5 to next 5

…. so on.

$start = ($page-1)*$records_per_page;

Step 8 & 9 : Retrieve selected result on page and close the database connection.

$selected_record = "SELECT * FROM data LIMIT " .$start.','.$records_per_page;
$selected_data = mysqli_query($conn, $selected_record);

Now we have to fetch the selected records on webpage by running a while loop.

<div style="height: 150px;">
   <?php
  while($row = mysqli_fetch_array($selected_data)):
      echo $row['id']. " " . $row['Alphabets']. '<br>';
  endwhile;

   // close the database connection as we don't requie remain open any more.	
   mysqli_close($conn);
   ?>
</div>

Step 10 : Making page links.

Creating Previous Link

if($page > 1){
   $prv  = $page - 1;
   echo '<span><a href="pagination.php?page='.$prv.'" class="page">Previous</a></span>';
}

This code execute the previous link when user user visits greater then page number 1 like 2, 3 and so on.

10 easy steps to create simple pagination using PHP

Creating Page Link

for($page=1; $page<=$total_page;$page++){
    if($page == $_GET['page'])
    {
        // on current page we do not need link 
  echo "<span class='a'>".$page."</span>";
    }else
  {
      echo '<a href="pagination.php?page='.$page.'"> ' . $page . ' </a>';
  }
}

Creating Next Link

$check = $start + $records_per_page;	
  
if($total_records > $check)
{
   if(!isset($_GET['page']))
   {
       $nxt = 2;
   }else
       {
        $nxt  = $_GET['page'] + 1;
       }
echo '<a href="pagination.php?page='.$nxt.'" class="page">Next</a>';
}

This code will execute only when user visits on less than last page other wise it will remain disappear.

10 easy steps to create simple pagination using PHP

Leave a Reply

You have to agree to the comment policy.

  1. varun says:

    hello, Naresh bhaiya.. query form bhi lga lo..

    1. Naresh Pal says:

      I will do soon….

  2. Great Tutorial! This PHP pagination tutorial have all the options. But I think it would be better if you add an option to change the total number of results. What do you think about it?