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.

This site is a digital habitat of Sameer Borate, a freelance web developer working in PHP, MySQL and WordPress. I also provide web scraping services, website design and development and integration of various Open Source API's. Contact me at metapix[at]gmail.com for any new project requirements and price quotes.

41 Responses

1

valchazzz

October 31st, 2008 at 12:48 am

Why mysql_num_rows ? Its slow, needs to select count(column) – its more efective.

sameer

October 31st, 2008 at 5:36 am

Ir’s just an example. You will notice that I’ve used count(*) in the second example.

3

Sameer’s Blog: Simple Pagination in PHP tutorial : WebNetiques

October 31st, 2008 at 6:23 am

[...] has posted a new tutorial to his blog recently, a look at a drop-in solution for pagination in your application – the PEAR [...]

4

cx42net

November 1st, 2008 at 10:05 am

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 :)

sameer

November 1st, 2008 at 8:16 pm

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.

6

Sameer’s Blog: Simple Pagination in PHP tutorial : Dragonfly Networks

November 3rd, 2008 at 3:09 pm

[...] has posted a new tutorial to his blog recently, a look at a drop-in solution for pagination in your application – the PEAR [...]

7

Emma

November 4th, 2008 at 2:49 am

Thanks so much for this simple but outstanding tutorial ive been looking for it for a while thanks so much.

8

Alex

November 7th, 2008 at 1:08 pm

I tried to use the script but it “hides” the last table row :S

sameer

November 7th, 2008 at 9:29 pm

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

$from = $from – 1;

I’ve updated the same above.

10

Alex

November 10th, 2008 at 7:52 am

Sweet, it works!! Thanks so much Sameer!!!

11

Dany

April 30th, 2009 at 5:41 am

Excellent! Thank you very much! i cant tell you just how happy I am.

12

Sumit

May 20th, 2009 at 8:23 am

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?

sameer

May 20th, 2009 at 10:07 am

Don’t know what search variable you are talking about. Can you elaborate it further.

14

Nasir

June 1st, 2009 at 10:54 am

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

15

Nasir

June 1st, 2009 at 10:56 am

sorry about wrong comment, I havn’t read with care earlier

16

Sue

July 25th, 2009 at 10:49 am

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

sameer

July 25th, 2009 at 9:35 pm

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

18

Nikita

August 3rd, 2009 at 2:38 pm

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

19

Mehedi Hasan

September 5th, 2009 at 1:40 am

WOW!!! Great tools. Thanks for sharing…. :)

20

Martin

November 6th, 2009 at 6:39 pm

excellent tutorial. Thanks

21

mike

November 8th, 2009 at 7:43 pm

sameer, thanks for this code. it’l help me alot on my project! your site has been bookmarked!

22

Benjamin

December 17th, 2009 at 3:21 pm

Would you please show me how the “Pager/Pager.php” page looks like… Thank you.

sameer

December 17th, 2009 at 8:28 pm

I did not really get your question. The Pager.php is here:

http://pear.php.net/package/Pager/download

Or do you want to look at a demo pagination page?

24

rancho

December 23rd, 2009 at 5:57 am

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'];

sameer

December 23rd, 2009 at 10:09 pm

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

26

Martin

March 8th, 2010 at 10:14 am

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.

sameer

March 8th, 2010 at 9:44 pm

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

28

Using PEAR Pager with PHP PDO | Abby and Win's Blog

March 16th, 2010 at 11:22 am

[...] Here’s a tutorial I found that helped me out a lot – http://www.codediesel.com/php/simple-pagination-in-php/. [...]

29

Hyder

May 16th, 2010 at 11:11 am

Nice article .nowadays there’s another sort of pagination similar to facebook and twitter .
it’s worth reading , see it guys
http://youhack.me/2010/05/14/an-alternative-to-pagination-facebook-and-twitter-style/

30

Annie

August 25th, 2012 at 5:52 am

Thank you for this code

31

ANKUR

October 25th, 2012 at 1:13 am

<?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>> “;
}

?>

32

Mark angelo

October 28th, 2012 at 10:30 am

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

33

Mark angelo

October 28th, 2012 at 10:34 am

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

34

bibin

January 18th, 2013 at 10:15 pm

very nice one helped me thank you soo much

35

Zoya Lane

January 22nd, 2013 at 2:52 am

This is really a great help.As i am newbie in php i have no idea of pagination and its working.

36

vivek

February 21st, 2013 at 5:47 am

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

sameer

February 21st, 2013 at 6:27 am

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.

38

Sharaz nabi

April 3rd, 2013 at 4:59 am

Really very helpfull information……
Thanks a lot..!!@@!!

39

Soundr

April 24th, 2013 at 4:16 am

Thanx…

40

Show Next and Previous records using php

May 11th, 2013 at 7:23 pm

[...] Here is a link to pagination code, although it's always advisable to pay a small commission to a developer and have it custom-coded to your specific needs: http://www.codediesel.com/php/simple-pagination-in-php/ [...]

41

Abdul Wali

November 22nd, 2014 at 4:17 pm

Very well explained and was very helpful. Thanks!

Your thoughts

Sign up for fresh content in your email