Simple Pagination in PHP tutorial

Pagination is a frequent requirement in web development projects. Most PHP developers must have already implementated paging in one form or other in their projects. In this post we will see how to add pagination the easy way using PEAR’s Pager class. Note that in all the posts I use PHP 5.x.x, so if you are still stuck at version 4.x.x, its already time to upgrade.

Its always nice to see some working code first, before getting into the details. So here goes.

require_once 'Pager/Pager.php';
/* We will bypass the database connection code ... */
$sqlQuery = "SOME SQL QUERY";
$result = mysql_query($sqlQuery);
$totalRows = mysql_num_rows($result);
 
$pager_options = array(
'mode'       => 'Sliding',
'perPage'    => 10,
'delta'      => 4,
'totalItems' => $totalRows,
);
$pager = Pager::factory($pager_options);
echo $pager->links;

The above code will return the following pagination links.

1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 » [10]

Assuming the page where the above code is included is named ‘dataPage.php'; the pager links will have a url like follows:

dataPage.php?pageID=n

where n is the page number.

You can see how easy it is using the Pager class. All the link building is handled by the class. Now lets go into the details.

1. Installation

If you are installing using the Pear installer, enter the following at the command prompt to install Pager.

c:\pear install Pager

Or else you can just download the module from here and then copy it to your Pear includes directory, which will probably be ‘c:\your php installation directory\Pear’.

2. A simple example

In the following example we will create a pagination for a ‘logs’ table.

/* Include the Pear::Pager file */
require_once ('Pager/Pager.php');
 
/* Replace this with your database details */
$connection = mysql_connect("localhost", username, password);
mysql_select_db(database name, $connection);
 
/* First we need to get the total rows in the table */
$result=mysql_query("SELECT count(*) AS total FROM logs", $connection);
$row = mysql_fetch_array($result);
 
/* Total number of rows in the logs table */
$totalItems = $row['total'];
 
/* Set some options for the Pager */
$pager_options = array(
'mode'       => 'Sliding',   // Sliding or Jumping mode. See below.
'perPage'    => 10,   // Total rows to show per page
'delta'      => 4,   // See below
'totalItems' => $totalItems,
);
 
/* Initialize the Pager class with the above options */
$pager = Pager::factory($pager_options);
 
/* Display the links */
echo $pager->links;
 
/* The following code will retreive the result using the pager options */
 
/* The function below will get the page offsets to be used with
the database query. For e.g if we are on the third page then the
$from variable will have the value of '21' (we are showing 10 items per 
page, remember) and the $to variable will have the value of '30'.
*/
list($from, $to) = $pager->getOffsetByPageId();
/* The MySQL 'LIMIT' clause index starts from '0', 
    so decrease the $from by 1 */
$from = $from - 1;
 
/* The number of rows to get per query */
$perPage = $pager_options['perPage'];
 
$result = mysql_query("SELECT * FROM alogs LIMIT $from , $perPage",
$connection);
 
while($row = mysql_fetch_array($result))
{
/* Do something with the query results */
}

In the Pager class there are two modes to display the pagination: Sliding & Jumping.

With Pager in “Sliding” mode the pagination links change smoothly, and the current page is always shown at the center of the “window” (except for the start and end pages). When in Sliding mode the delta option implies how many links to show on the left and right of the current page link.
For e.g with a delta set to ‘3’ the links are displayed as shown below, page 10 being the current page:

[1] « 7 | 8 | 9 | 10 | 11 | 12 | 13 » [13]

With delta option set to ‘4’ the links are shown as below. As you can see there are four links to the left and right of the current page.

[1] « 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 » [13]

With the Pager in “Jumping” mode and delta set to ‘4’ the Pager always shows the same 4 page links while you are on one of these pages.
For e.g with a delta set to ‘4’ the links are displayed as shown below, page 5 being the current page:

[1] << Back 5 6 7 8  Next >> [13]

If you are on page ‘9’ the links displayed are as below:

[1] << Back 9 10 11 12  Next >> [13]

3. More options

You can also change the default separator to any character or image you like.

$pager_options = array(
'mode'       => 'Sliding',
'perPage'    => 10,
'delta'      => 4,
'separator' => ',',
'totalItems' => $totalItems,
);

This will output the following:
[1] « 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 » [13]

If you would like to add images to the ‘next’ and ‘previous’ links, use the following options:

$pager_options = array(
'mode'       => 'Sliding',
'perPage'    => 10,
'delta'      => 4,
'nextImg'    => '<img src="next.png"  />',
'prevImg'    => '<img src="prev.png"  />',
'totalItems' => $totalItems,
);

Which will display the links as shown below:

The default number of spaces before each separator is three. To change the number of spaces use the ‘spacesBeforeSeparator’ option. For e.g:

.
.
'spacesBeforeSeparator' => 1,
.

4. Styling

You can style the links by putting them in a div tag and applying a css. A example css and its output is shown below.

Add a div tag:

.
.
echo '<div class="pager">';
echo $pager->links;
echo '</div>';

Apply CSS:

.pager {
    font-family: Arial;
    font-size: 14px;
}
 
.pager a {
    font-family: Arial;
    font-size: 14px;
    text-decoration: none;
    width: 17px;
    height: 17px;
    border: 1px solid #000;
    background-color: #0C74BA;
    text-align: center;
    color: #fff;
}
 
.pager a:hover {
    background-color: #c0c0c0;
}

The output:
pager

That’s it. There are many other options you can use with the Pager class, the details which you can find in the Pager documentation.



43 thoughts on “Simple Pagination in PHP tutorial

  1. Why not use PDO ?

    All the mysql_* are deprecated (kind of) now, so I don’t know why a lot of people continues to use mysql_*.

    What are your thought about that ? I’m interesting to know why you’re using these functions :)

  2. I wrote this tutorial for a beginner-intermediate PHP programmer. I wanted to keep the focus on the pagination code rather then on the database As many new PHP programmer still don’t use PDO or any other database abstraction layer, I felt it was necessary to keep the database part simple. Someone using PDO can easily adapt the above without much changes.

  3. Add the following line after list($from, $to) = $pager->getOffsetByPageId();

    $from = $from – 1;

    I’ve updated the same above.

  4. Good stuff. While using the code I have faced the problem. The search string variable does not pass to the next page. I simply get the first page alright with search string but from the 2nd page onward it displays the data from the database. Can you pl. help me?

  5. I understand all things but where is the pager.php file which you have included in script???

  6. Is there a way to change the root url for pagination? For instance right now when I hover over the links, it takes me to index.php?pageID=n rather than to /category/index.php?cat=somecategory&pageID=n or category/index.php?page=3

  7. You can add the path to the pager options as below:

    $pager_options = array(
    ‘mode’ => ‘Sliding’, // Sliding or Jumping mode. See below.
    ‘perPage’ => 10, // Total rows to show per page
    ‘delta’ => 4, // See below
    ‘path’ => ‘/category’,
    ‘totalItems’ => $totalItems,
    );

    You can find out more about the various options here:

    http://pear.php.net/manual/en/package.html.pager.factory.php

  8. Hi Admin and Other Readers of this Post!

    I am on Windows XP with Working PHP 5.2 and wish to use this PHP pagination class[as name suggests]. How should I go about installing it on my computer with PHP running.

    I dont want to use require_once or include_once statements also, how can I edit these scripts to do so and run [install] on my computer.

    Can you help?

    For clarfication you can email me in plain txt, pls include your email-id in plain txt as reply.

    Rgds,
    Niki

  9. use your code,it works fine,but i have one question, in a webpage where i used your pagination script , where we previously wrote the no of item per page we want to show,but i want to do that ,when any user see my website he has a option that how many item he wants to show per page,suppose Show Item Per Page:10|20|30|40.How can i do this ?Please help me.
    this is my code:
    require_once (‘Pager/Pager.php’);
    $result=mysql_query(“SELECT count(*) AS total FROM product where product_name LIKE ‘a%'; “);
    $row = mysql_fetch_array($result);
    $totalItems = $row[‘total’];
    $pager_options = array(
    ‘mode’ => ‘Sliding’,
    ‘perPage’ => 2,
    ‘delta’ => 4,
    //’separator’ => ‘,’,
    ‘totalItems’ => $totalItems,
    );
    $pager = Pager::factory($pager_options);
    echo $pager->links;
    list($from, $to) = $pager->getOffsetByPageId();
    $from = $from – 1;
    $perPage = $pager_options[‘perPage’];

  10. Hello Rancho, you could create a drop-down with the items to show per page. After selecting the drop-down, you could pass then set the per page items in a session, $_SESSION[‘perPage’] and then use it in your code.

    $pager_options = array(
    ‘mode’ => ‘Sliding’,
    ‘perPage’ => $_SESSION[‘perPage’] ,
    ‘delta’ => 4,
    //’separator’ => ‘,’,
    ‘totalItems’ => $totalItems,
    );

  11. How can you carry over your own variables into the URL?

    I am using a form to POST a couple of variables (firstname and surname). The first page that is generated is fine, however pressing on page 2 then looses all the variables that have been posted which then displays the either contents of database.

    quick example:

    $perPage = $pager_options['perPage'];

    $result = mysql_query("SELECT * FROM table WHERE person_firstname LIKE '%$firstname%' AND person_surname LIKE '%$surname%' LIMIT $from , $perPage", $connection);

    I am presuming I need to add something to the $pager_options but I can’t figure out which part of Pager::factory() to use.

  12. You can add extra GET variables in the options array as below:

    $pager_options = array(
    ‘mode’ => ‘Sliding’, // Sliding or Jumping mode. See below.
    ‘perPage’ => 10, // Total rows to show per page
    ‘delta’ => 4, // See below
    ‘totalItems’ => $totalItems,

    ‘extraVars’ => array(
    ‘firstName’ => ‘John’,
    ‘LastName’ => ‘Gates’)
    );

  13. <?php
    //simple code for pagination from database.
    $link=mysql_connect('localhost','root','');
    if(!$link)
    {
    die('could not connect'.mysql_error());
    }
    else
    {
    //echo "connected successfully";
    //echo "”;
    }
    mysql_select_db(“bestprice”);

    $totalrec = 0;

    //echo “totol number of records in table are”.”$totalrec Rows\n”;
    //echo “”;
    $limit=5;

    //echo $pages;
    $p=isset($_GET[‘p’])?$_GET[‘p’]:1;
    $s=($p-1)*$limit;

    $query=”SELECT COUNT(snum) as cnt,snum,item,price,type FROM shop LIMIT $s,$limit”;
    //echo $query;
    $show=mysql_query($query,$link);
    $resArr=array();
    $i=0;
    while($row=mysql_fetch_array($show))
    {
    echo $totalrec=$row[‘cnt’];
    echo “shop number is “.$resArr[$i][‘snum’] = $row[‘snum’];
    echo “”;
    echo “item is = “.$resArr[$i][‘item’] = $row[‘item’];
    echo “”;
    echo “type of item is= “.$resArr[$i][‘type’] = $row[‘type’];
    echo “”;
    echo “price of item is= “.$resArr[$i][‘price’] = $row[‘price’];
    echo “”;
    echo “”;
    echo “”;
    $i++;

    }
    $pages=ceil($totalrec/$limit);

    if($p>1)
    {
    echo “ << previous “;
    }

    for($j=1;$j<=$pages;$j++)
    {
    if($j==1)
    {
    echo " $j “;
    }
    else
    {
    echo ” | $j “;
    }

    }
    if($p<$pages)
    {
    echo " next>> “;
    }

    ?>

  14. Strict Standards: Non-static method Pager::factory() should not be called statically in C:\xampp\htdocs\hello\index.php on line 26

  15. Strict Standards: Non-static method Pager::factory() should not be called statically in C:\xampp\htdocs\hello\index.php on line 26

    this gives me error ?? T.T

  16. exactly where to put pager.php file in php file system, cause php/pear/ already have pager.php file and pager folder? rply soon…..great work sameer

  17. If you have installed Pear pager correctly, then just include the correct path to the same. Use the PHP ‘set_include_path’ function to set the path to the Pear Pager directory, wherever that is on your server.

  18. hello, sameer thanks for the very nice tutorial…but i am stuck with one problem…the pagination works fine for the first page but when i click on 2 to view the second page it says the variable ‘id’ is undefined…the part where i have defined the id is give below:
    include(‘db.php’);
    include(‘Pager.php’);
    $id=$_POST[‘id’];
    $query=”select * from tbl_student where groups=’$id'”;

    can u please suggest me on that!!!

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>