Advertisement

How to Paginate Data with PHP

by
Student iconAre you a student? Get a yearly Tuts+ subscription for $45 →

I can remember years ago when I first began coding in PHP and MySQL, how excited I was the first time I got information from a database to show up in a web browser. For someone who had little database and programming knowledge, seeing those table rows show up onscreen based on the code I wrote (okay so I copied an example from a book -- let's not split hairs) gave me a triumphant high. I may not have fully understood all the magic at work back then, but that first success spurred me on to bigger and better projects.

While my level of exuberance over databases may not be the same as it once was,
ever since my first 'hello world' encounter with PHP and MySQL I've been hooked
on the power of making things simple and easy to use. As a developer, one problem
I'm constantly faced with is taking a large set of information and making it easy
to digest. Whether its a large company's client list or a personal mp3 catalog,
having to sit and stare at rows upon rows upon rows of data can be discouraging
and frustrating. What can a good developer do? Paginate!


1. Pagination

Pagination is essentially the process of taking a set of results and spreading
them out over pages to make them easier to view.

example 1

I realized early on that if I had 5000 rows of information to display not only
would it be a headache for someone to try and read, but most browsers would take
an Internet eternity (i.e. more than about five seconds) to display it. To solve
this I would code various SQL statements to pull out chunks of data, and if I was
in a good mood I might even throw in a couple of "next" and "previous" buttons.
After a while, having to drop this code into every similar project and customize
it to fit got old. Fast. And as every good developer knows, laziness breeds inventiveness
or something like that. So one day I sat down and decided to come up with a simple,
flexible, and easy to use PHP class that would automatically do the dirty work for
me.

A quick word about me and PHP classes. I'm no object-oriented whiz. In fact I hardly
ever use the stuff. But after reading some OOP examples and tutorials, and some
simple trial and error examples, I decided to give it a whirl and you know what?
It works perfectly for pagination. The code used here is written in PHP 4 but will
work in PHP 5.


2. The Database

Gotta love MySQL. No offense to the other database systems out there, but for
me all I need is MySQL. And one great feature of MySQL is that they give you some
free sample databases to play with at
http://dev.mysql.com/doc/#sampledb.
For my examples I'll be using the world database (~90k zipped) which contains over
4000 records to play with, but the beauty of the PHP script we'll be creating is
that it can be used with any database. Now I think we can all agree that if we decided
not to paginate our results that we would end up with some very long and unwieldy
results like the following:

example 2

(click for full size, ridiculously long image ~ 338k)

So lets gets down to breaking up our data into easy to digest bites like this:

example 3

Beautiful isn't it? Once you drop the pagination class into your code you can
quickly and easily transform a huge set of data into easy to navigate pages with
just a few lines of code. Really.


3. Paginator.class.php

Our examples will use just two scripts: paginator.class.php, the reusable
pagination script, and index.php, the PHP page that will call and use
paginator.class.php. Let's take a look at the guts of the pagination class
script.

<?php

class Paginator{
    var $items_per_page;
    var $items_total;
    var $current_page;
    var $num_pages;
    var $mid_range;
    var $low;
    var $high;
    var $limit;
    var $return;
    var $default_ipp = 25;

    function Paginator()
    {
        $this->current_page = 1;
        $this->mid_range = 7;
        $this->items_per_page = (!empty($_GET['ipp'])) ? $_GET['ipp']:$this->default_ipp;
    }

    function paginate()
    {
        if($_GET['ipp'] == 'All')
        {
            $this->num_pages = ceil($this->items_total/$this->default_ipp);
            $this->items_per_page = $this->default_ipp;
        }
        else
        {
            if(!is_numeric($this->items_per_page) OR $this->items_per_page <= 0) $this->items_per_page = $this->default_ipp;
            $this->num_pages = ceil($this->items_total/$this->items_per_page);
        }
        $this->current_page = (int) $_GET['page']; // must be numeric > 0
        if($this->current_page < 1 Or !is_numeric($this->current_page)) $this->current_page = 1;
        if($this->current_page > $this->num_pages) $this->current_page = $this->num_pages;
        $prev_page = $this->current_page-1;
        $next_page = $this->current_page+1;

        if($this->num_pages > 10)
        {
            $this->return = ($this->current_page != 1 And $this->items_total >= 10) ? "<a class=\"paginate\" href=\"$_SERVER[PHP_SELF]?page=$prev_page&ipp=$this->items_per_page\">« Previous</a> ":"<span class=\"inactive\" href=\"#\">« Previous</span> ";

            $this->start_range = $this->current_page - floor($this->mid_range/2);
            $this->end_range = $this->current_page + floor($this->mid_range/2);

            if($this->start_range <= 0)
            {
                $this->end_range += abs($this->start_range)+1;
                $this->start_range = 1;
            }
            if($this->end_range > $this->num_pages)
            {
                $this->start_range -= $this->end_range-$this->num_pages;
                $this->end_range = $this->num_pages;
            }
            $this->range = range($this->start_range,$this->end_range);

            for($i=1;$i<=$this->num_pages;$i++)
            {
                if($this->range[0] > 2 And $i == $this->range[0]) $this->return .= " ... ";
                // loop through all pages. if first, last, or in range, display
                if($i==1 Or $i==$this->num_pages Or in_array($i,$this->range))
                {
                    $this->return .= ($i == $this->current_page And $_GET['page'] != 'All') ? "<a title=\"Go to page $i of $this->num_pages\" class=\"current\" href=\"#\">$i</a> ":"<a class=\"paginate\" title=\"Go to page $i of $this->num_pages\" href=\"$_SERVER[PHP_SELF]?page=$i&ipp=$this->items_per_page\">$i</a> ";
                }
                if($this->range[$this->mid_range-1] < $this->num_pages-1 And $i == $this->range[$this->mid_range-1]) $this->return .= " ... ";
            }
            $this->return .= (($this->current_page != $this->num_pages And $this->items_total >= 10) And ($_GET['page'] != 'All')) ? "<a class=\"paginate\" href=\"$_SERVER[PHP_SELF]?page=$next_page&ipp=$this->items_per_page\">Next »</a>\n":"<span class=\"inactive\" href=\"#\">» Next</span>\n";
            $this->return .= ($_GET['page'] == 'All') ? "<a class=\"current\" style=\"margin-left:10px\" href=\"#\">All</a> \n":"<a class=\"paginate\" style=\"margin-left:10px\" href=\"$_SERVER[PHP_SELF]?page=1&ipp=All\">All</a> \n";
        }
        else
        {
            for($i=1;$i<=$this->num_pages;$i++)
            {
                $this->return .= ($i == $this->current_page) ? "<a class=\"current\" href=\"#\">$i</a> ":"<a class=\"paginate\" href=\"$_SERVER[PHP_SELF]?page=$i&ipp=$this->items_per_page\">$i</a> ";
            }
            $this->return .= "<a class=\"paginate\" href=\"$_SERVER[PHP_SELF]?page=1&ipp=All\">All</a> \n";
        }
        $this->low = ($this->current_page-1) * $this->items_per_page;
        $this->high = ($_GET['ipp'] == 'All') ? $this->items_total:($this->current_page * $this->items_per_page)-1;
        $this->limit = ($_GET['ipp'] == 'All') ? "":" LIMIT $this->low,$this->items_per_page";
    }

    function display_items_per_page()
    {
        $items = '';
        $ipp_array = array(10,25,50,100,'All');
        foreach($ipp_array as $ipp_opt)    $items .= ($ipp_opt == $this->items_per_page) ? "<option selected value=\"$ipp_opt\">$ipp_opt</option>\n":"<option value=\"$ipp_opt\">$ipp_opt</option>\n";
        return "<span class=\"paginate\">Items per page:</span><select class=\"paginate\" onchange=\"window.location='$_SERVER[PHP_SELF]?page=1&ipp='+this[this.selectedIndex].value;return false\">$items</select>\n";
    }

    function display_jump_menu()
    {
        for($i=1;$i<=$this->num_pages;$i++)
        {
            $option .= ($i==$this->current_page) ? "<option value=\"$i\" selected>$i</option>\n":"<option value=\"$i\">$i</option>\n";
        }
        return "<span class=\"paginate\">Page:</span><select class=\"paginate\" onchange=\"window.location='$_SERVER[PHP_SELF]?page='+this[this.selectedIndex].value+'&ipp=$this->items_per_page';return false\">$option</select>\n";
    }

    function display_pages()
    {
        return $this->return;
    }
}
?>

Phew, that's a lot of code! But don't worry, I'll explain what all the
different parts do and how they're used.


4. Have a Little Class

Let's begin at the beginning. First off we declare the class and give it a
name. Paginator should do it. And while we're at it, let's set some variables,
or properties in OOP speak, that our new paginator object will use.

class Paginator{
    var $items_per_page;
    var $items_total;
    var $current_page;
    var $num_pages;
    var $mid_range;
    var $low;
    var $high;
    var $limit;
    var $return;
    var $default_ipp = 25;

We start off our class by giving it a name, in this case "Paginator", and
defining the variables (a.k.a the properties of an object) that we'll be using.
When we create a new object using this class (a.k.a instantiating), the object
will have these properties and one of them, $default_ipp (the default number of
items per page), is also initialized to a value of 25.

Our class will have five methods, or
member functions, which do the heavy lifting; and they're named Paginator, paginate,
display_items_per_page, display_jump_menu, and display_pages.

function Paginator()
{
    $this->current_page = 1;
    $this->mid_range = 7;
    $this->items_per_page = (!empty($_GET['ipp'])) ? $_GET['ipp']:$this->default_ipp;
}

The Paginator function is also referred to as our constructor method, which just means when you
create a new paginator object, this function is also called by default. When we instantiate a new paginator
object, this initializes it with some default values. Here we set those
variables and check to see if we've changed the number of items per page to
display. If the items per page variable isn't set in the URL's query string ($_GET['ipp']),
we use the default number when the class was created.

The next method, the paginate function, is the Arnold Schwarzenegger, the Jean Claude Van Damme, the
meat of our class. The paginate method is what determines how many page
numbers to display, figures out how they should be linked, and applies CSS
for styling.

if($_GET['ipp'] == 'All')
{
    $this->num_pages = ceil($this->items_total/$this->default_ipp);
    $this->items_per_page = $this->default_ipp;
}
else
{
    if(!is_numeric($this->items_per_page) OR $this->items_per_page <= 0) $this->items_per_page = $this->default_ipp;
    $this->num_pages = ceil($this->items_total/$this->items_per_page);
}

The first part of this method determines the number of pages we'll be
outputting and sets the number of items per page. First it tests to see if we
want to display all the items on one page. If so, it simply displays all the
items on one page and if not, it calculates the number of links it will need to
output, based on the number of items per page and the total number of items. It
also throws in some error checking to make sure that the number of items per
page is a numeric value.

$this->current_page = (int) $_GET['page']; // must be numeric > 0
if($this->current_page < 1 Or !is_numeric($this->current_page)) $this->current_page = 1;
if($this->current_page > $this->num_pages) $this->current_page = $this->num_pages;
$prev_page = $this->current_page-1;
$next_page = $this->current_page+1;

The next part gets the page number we're on and checks to make sure that it's
a number in a valid range. It also sets the previous and next page links.

The rest of the paginate method is what does all the hard work. We check to
see if we have more than  ten pages (if($this->num_pages > 10)), ten
being a number that you can easily change. If
we don't have more than ten pages, we simply loop from one to however many pages
we do have, and link them up accordingly. We don't display any previous page or next page
links since we're displaying all page numbers and this would be a bit redundant, but
we do display a link to all items. If we have more than ten pages, then
instead of displaying links to each and every page (if we had say 200 pages to
display, things might get a little ugly), we display links to the first and last
page and then a range of pages around the current page that we're on. This is
where the variable (property) $this->mid_range comes into play. This variable tells the
paginator how many page numbers to display between the first and last pages. By
default this is set to seven, however you can change it to anything you like.
Just a note, the mid range value should be an odd number so the display is
symmetrical, but it can be even if you like. For example, let's say we have 4000
rows of data in all, and we're viewing 50 rows of data per page. That gives us
79 pages to display, but aside from the first and last pages we're
only going to display links to three pages above and below the page we're on. So
if we're on page 29, the paginator will display links to page 1, 26, 27, 28, 29,
30, 31, 32, and 79 (don't worry, if you want to jump to a specific page not in
that range I'll explain how to do that a little later on). As you move
closer to the upper and lower page limits, the mid range adjusts itself so that
you always have at least the number of page links that mid_range is set for.

The next method, display_items_per_page, is an optional method that will display a drop
down menu that allows a visitor to change the number of items displayed per
page. The default values for the drop down menu are 10, 25, 50, 100, and
All. You can change the numeric values to anything you like, but if you want to
retain the 'All' option, it must not be changed

items per page.
function display_items_per_page()
{
    $items = '';
    $ipp_array = array(10,25,50,100,'All');
    foreach($ipp_array as $ipp_opt)    $items .= ($ipp_opt == $this->items_per_page) ? "<option selected value=\"$ipp_opt\">$ipp_opt</option>\n":"<option value=\"$ipp_opt\">$ipp_opt</option>\n";
    return "<span class=\"paginate\">Items per page:</span><select class=\"paginate\" onchange=\"window.location='$_SERVER[PHP_SELF]?page=1&ipp='+this[this.selectedIndex].value;return false\">$items</select>\n";
}

The next method, display_jump_menu, is another optional method that displays a drop down
menu that will list all the page numbers available and allow a visitor to
jump directly to any page. Using our previous example, if we had a total of
79 pages to display, this drop down menu would list them all so that when
someone selects a page, it automatically will take them to it.

function display_jump_menu()
{
    for($i=1;$i<=$this->num_pages;$i++)
    {
        $option .= ($i==$this->current_page) ? "<option value=\"$i\" selected>$i</option>\n":"<option value=\"$i\">$i</option>\n";
    }
    return "<span class=\"paginate\">Page:</span><select class=\"paginate\" onchange=\"window.location='$_SERVER[PHP_SELF]?page='+this[this.selectedIndex].value+'&ipp=$this->items_per_page';return false\">$option</select>\n";
}

The last method, display_pages, may be the shortest method, but it's also one
of the most important. This method displays the page numbers on your page.
Without calling it, all the calculations would be done, but nothing would be
shown to your visitor. You need to
call this method at least once in order to display your pagination, but you can also
use it more than once if you like. For example, you could display the page
numbers above AND below your results for convenience. And convenience is
what its all about, no?


5. So How Do I Use This Thing?

There are three things you need to do in your index.php file before being
able to use your new paginator class.

  1. First, include the paginator class in the page where you want to use it.
    I like to use require_once because it ensures that the class will only be
    included once and if it can’t be found, will cause a fatal error.
  2. Next, make your database connections.
  3. Finally, query your database to get the total number of records that
    you'll be displaying.

Step three is necessary so that the paginator can figure out how many records
it has to deal with. Typically the query can be as simple as SELECT COUNT(*)
FROM table WHERE blah blah blah.

You're almost there. Now it's time to create a new paginator object, call a
few of its methods, and set some options. Once you have your total record count
from step three above you can add the following code to index.php:

$pages = new Paginator;
$pages->items_total = $num_rows[0];
$pages->mid_range = 9;
$pages->paginate();
echo $pages->display_pages();

Let's break it down...

  • The first line gives us a shiny new paginator object to play with and
    initializes the default values behind the scenes.
  • The second line uses the query we did to get the total number of records and
    assigns it to our paginator's items_total property. $num_rows is an array
    containing the result of our count query (you could also use PHP's
    mysql_num_rows function to retrieve a similar count if you like).
  • The third line tells the paginator the number of page links to display. This
    number should be odd and greater than three so that the display is symmetrical.
    For example if the mid range is set to seven, then when browsing page 50 of 100,
    the mid range will generate links to pages 47, 48, 49, 50, 51, 52, and 53. The
    mid range moves in relation to the selected page. If the user is at either the
    low or high end of the list of pages, it will slide the range toward the other
    side to accommodate the position. For example, if the user visits page 99 of
    100, the mid range will generate links for pages 94, 95, 96, 97, 98, 99, and
    100.
  • The fourth line tell the paginator to get to work and paginate and finally the
    fifth line displays our page numbers.

If you decide to give your visitors the option of changing the number of items
per page or jumping to a specific page, you can add this code to index.php:

echo "<span style="\"margin-left:25px\""> ". $pages->display_jump_menu() 
. $pages->display_items_per_page() . "</span>";

If you stopped here and viewed your page without adding anything else, you'd see
your page numbers but no records. Aha! We haven't yet told PHP to display the
specific subset of records we want. To do that you create a SQL query that
includes a LIMIT statement that the paginator creates for you. For example, your
query could look like:

SELECT title FROM articles WHERE title != '' ORDER BY title ASC $pages->limit

$pages->limit is critical in making everything work and allows our paginator
object to tell the query to fetch only the limited number of records that we
need. For example, if we wanted to see page seven of our data, and we're viewing
25 items per page, then $pages->limit would be the same as LIMIT 150,25 in SQL.

Once you execute your query you can display the records however you like. If you
want to display the page numbers again at the bottom of your page, just use the
display_pages method again:

echo $pages->display_pages();

6. More Features

As an added bonus, the paginator class adds "Previous", "Next", and "All"
buttons around your page links. It even disables them when you're on the first
and last pages respectively when there are no previous or next pages. If you
like, you can also tell your visitors that they're viewing page x of y by using
the code:

echo "Page $pages->current_page of $pages->num_pages";

Styling

Finally, you're free to customize the look of your pagination buttons as much as
you want. With the exception of the current page button, all other page buttons
have the CSS class "paginate" applied to them while the current page button has,
can you guess, the "current" class applied to it. The "Previous" and "Next"
buttons will also have the class "inactive" applied to them automatically when
they're not needed so you can style them specifically. Using these three classes
along with other CSS gives you tremendous flexibility to come up with a variety
of styling choices.

Styled:

example 4

Unstyled:

example 5

Wrapping Up

As you've seen with the pagination class and just a few lines of code you can
tame those giant database lists into manageable, easy to navigate, paginated
lists. Not only are they easier on the eyes but they're faster not only to load
but to browse. Feel free to checkout a couple of demos at
example 1 and
example 2.

  • Subscribe to the NETTUTS RSS Feed for more daily web development tuts and articles.