Pagination Nation

How to Paginate Data with PHP

Feb 5th in PHP by Jason

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.

PG

Author: Jason

This is a NETTUTS contributor who has published 1 tutorial(s) so far here. Their bio is coming soon!

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!

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.

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.

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.

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?

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

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.


Related Posts

Check out some more great tutorials and articles that you might like

Enjoy this Post?

Your vote will help us grow this site and provide even more awesomeness

Plus Members

Source Files, Bonus Tutorials and
More for $9 a month for all TUTS+
sites in one subscription.

Join Now

User Comments

( ADD YOURS )
  1. PG

    Josh February 5th

    Finally a paginator!
    thanks

    ( Reply )
  2. PG

    Benjamin Falk February 5th

    Looks useful — I was about to get started on something similar for my blog. Thanks for the explanation, I’ll have to look at this in more detail.

    ( Reply )
  3. PG

    Cory Micek February 5th

    mmmm tasty

    ( Reply )
  4. PG

    Matt February 5th

    Excellent article, good details. Thanks!

    ( Reply )
  5. PG

    Andrea February 5th

    Great one! It’s possible to make a combination with jQuery, to make it work under AJAX?

    ( Reply )
  6. PG

    Corey February 5th

    Andrea, one solution could be something like this:
    ‘.$i.’‘;

    Then, in jQuery:
    $(’.paging a’).click(function() {
    var page_no = $(this).attr(’rel’);
    $.get(’page.php’, {page : page_no}, function(data) {
    $(’#container’).html(data);
    }
    return false;
    });

    ( Reply )
  7. PG

    Corey February 5th

    Andrea, one solution could be something like this:

    ‘<a href=”‘.$i.’” rel=”‘.$i.’”>’.$i.’</a>’;

    Then, in jQuery:

    $(’.paging a’).click(function() {
    var page_no = $(this).attr(’rel’);
    $.get(’page.php’, {page : page_no}, function(data) {
    $(’#container’).html(data);
    }
    return false;
    });

    ( Reply )
  8. PG

    Ellisgl February 5th

    Great job!

    ( Reply )
  9. PG

    DKumar M. February 5th

    Thanks Jason, Nice Article…. Also Thanks to Corey for JQuery Solution.

    ( Reply )
  10. PG

    Lee February 5th

    heyooo! great article.. heh was just working on a module that uses pagination.. It’s always great to have a pagination class in your toolbox

    ( Reply )
  11. PG

    M.A.Yoosuf February 5th

    great article on grat time, i was thinking for adding the Paging in my Clients product page and thank god, u did in a nice way,

    huoooora, now i can give a better solution with nettuts and you guys :P

    ( Reply )
  12. PG

    srganesan February 5th

    Thanks Jason.. excellent work :D

    ( Reply )
  13. PG

    insic February 5th

    well done! nice tutorial.

    ( Reply )
    1. PG

      marvinPH April 15th

      hi! i like u ur so cute.. :)

      ( Reply )
  14. PG

    Ivor February 5th

    Great Great tutorial, I’ve been waiting for this.!!

    ( Reply )
  15. PG

    Ian Tindale February 6th

    This form of user interface – the row of numbers underneath a large quantity of editorial or article content, or in your case, tabular information, is a ridiculous failure of usability.

    If I’m on ‘page’ 1, and I see a row underneath of
    1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,21,22,23,24,25,26,27,28,29, etc
    Why on earth would consider going to 11, or 17 or 25? I’ve absolutely no idea what I’d find there, and when I get there it’s highly likely it’s not what I actually wanted. The only reason you’d pick any number other than the neighbour of the one you’re presently on is through a wholly random high-risk guess. Important information shouldn’t be subjected to that sort of lottery or guessing game. All those interim numbers between where you are and the beginning or end of the sequence are fundamentally useless. You can’t be on ‘2′ and decide with any confidence at all that “aha, I’d better go to 16 to find what I want next”. The number ‘16′ tells you absolutely nothing at all. They might as well be pictures of random animals or simply dots of increasing shades, or better still, present a ’shoot the ducks’ game to the user instead – the chances of getting what you want would be about the same.

    ( Reply )
    1. PG

      ziggidy March 4th

      what if the user found something on page 28 and wanted to come back to it later. be it without bookmarking the page or anything.
      all they must do is remember the page number. ill admit that there may be some skepticism about this too, but its a thought.
      i think paginators like this are successfull, look around the web.

      ( Reply )
      1. PG

        PB July 2nd

        I agree with ziggidy. This works well for forums. Sometimes you’re reading through a forum and go through 5 pages. A couple days later the thread grows to 12 pages and you can come back and start right at page 5 without a bunch of clicking.

        Plus most editorial or article stay below 10 pages so your point is exaggerated. And for the cases that do, this example handles it with the jump to page form.

  16. PG

    3.5Nando February 6th

    You can also incorporate this Slider I’ve found lately http://og5.net/christoph/article/A_better_Pagination

    ( Reply )
  17. PG

    ThomasP February 6th

    Hey, thank you so much for that great tutorial. It’s far better than that stupid example in my php-book.
    Pleas post more of them soon! :)

    ( Reply )
  18. PG

    ali February 6th

    Hi dear,
    most useful tutorial.
    thanks.

    ( Reply )
  19. PG

    Christian Dalsvaag February 6th

    This was an excellect written article. Very nice details, and a nice class indeed.

    Thanks!

    ( Reply )
  20. PG

    OWZ February 6th

    Jason… great tutorial..

    I have a question about the 2nd example you have used..

    I’m trying to create something similar where the user selects a category and then the database pulls all the records which has the same category. Do you know where I could find a tutorial on this.. As its exactly what Im trying to work out for a current project..

    Thank you..

    ( Reply )
  21. PG

    Abhijit February 6th

    Very very good tutorial. Thanks. By the way you have used PHP 4 style classes, is there any specific reason for this?

    ( Reply )
  22. PG

    Matt February 6th

    Thanks for posting this. Very useful.

    I did however find some errors in the downloadable code. I managed to fix these myself but thought I should just mention in case anyone else is wondering why it doesn’t work.

    I assume you uploaded a development version of the code by mistake rather than the final one. Maybe you could check and upload the correct version.

    ( Reply )
  23. PG

    cirano February 6th

    Tnx for a nice article. Maybe I missed it, but will content that is initially positioned on page 5 remain on that page after you add more content to that database or will it move to page 6?

    ( Reply )
  24. PG

    Maik Diepenbroek February 6th

    Nice detailed tutorial thanks.

    ( Reply )
  25. PG

    Timothy February 6th

    Seems a bit complicated. I just paginate within MySQL using the LIMIT and OFFSET commands. Rather than pulling down all the records I pull down about 15-25 and update via MooTools / Ajax when a user pages. It works well.

    The performance difference in these cases is pretty marginal if you are just pulling from a small table, but if you are pulling from a table with thousands(+) records you will see a difference.

    ( Reply )
  26. PG

    Jens February 6th

    I think it’s bad to return html code in a php class. Not very handy if you want to change the template or something. Then you’ll have to change the html code in two pages instead of one.

    ( Reply )
  27. PG

    Kevin Quillen February 6th

    Performance should be considered for a real site where you could have upwards of a few thousand or more items.

    ( Reply )
  28. PG

    Chris Southam February 6th

    Adding SQL_CALC_FOUND_ROWS to the beginning of the query after SELECT will produce the number of results that would have returned if you hadn’t limited the recordset.

    Can’t recommend it enough – combined with this
    $RS_EmployeeCount = mysql_fetch_array(mysql_query(”SELECT FOUND_ROWS() AS Total”));
    $EmployeeCount = $RS_EmployeeCount["Total"];

    I’ve found it less of a performance hit than two queries – one to count all rows and the other to produce the results + neater/less code.

    ( Reply )
  29. PG

    Pete February 6th

    Good LORD, have fun debugging that behemoth. Think maybe Drupal or .NET would tend to be a slightly easier approach?

    ( Reply )
  30. PG

    nibbo February 6th

    Doesn’t the way he uses LIMIT gives the same result as a combination of LIMIT and OFFSET. LIMIT 5,5 is supposed to give the same effect as OFFSET 5 LIMIT 5.

    Thanks for the tutorial! Well done :)

    ( Reply )
  31. PG

    Shaun February 6th

    This a great tutorial, just what I’ve been looking for!

    However, I am having problems getting it to work correctly!

    I keep getting a SQL Syntax Error, saying there is a problem in my Syntax, I’ve echo’d the query to see what is wrong and this is what I got:

    “SELECT * FROM caravans ORDER BY C_PRICE ASC LIMIT -25,25;

    You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘-25,25′ at line 1″

    I’m not an expert, but as far as I can see its trying to start at row number -25

    My query is as follows:

    “SELECT * FROM caravans ORDER BY C_PRICE ASC $pages->limit;”

    Any help would be great?!?

    Regards

    Shaun

    ( Reply )
  32. PG

    Kevin Quillen February 6th

    Wait, why is there so much code?

    ( Reply )
  33. PG

    tom stovall February 6th

    Just did something similar at the office, only the calls to get paginated data were ajaxed JS calls.

    ( Reply )
  34. PG

    ashvin February 6th

    nice tut. thanx a lot.

    ( Reply )
  35. PG

    Jafster February 6th

    Nice one, but as im used to rails, i dont like the way to mix html and php code. Very confusing. I would still use rails mislav-will_paginate gem for this.

    ( Reply )
  36. PG

    Jeremy February 6th

    Great tut! Saved me HOURS of work.

    ( Reply )
  37. PG

    weblizzer February 6th

    great tut, but i have also made my own different in this.. but great post.

    ( Reply )
  38. PG

    Jamie Taniguchi February 6th

    Interesting topic for your first tutorial. The class seems a bit bloated, I don’t necessarily agree with the approach taken here but I’m not about to nitpick ;) However, what I would like to point out is that with the current query this is not scalable for larger data sets. While, your examples may seem speedy now, with 10,000 records you will notice a hit to performance. ie: if your limit looked something like LIMIT 10000, 20 you’re generating 10,020 rows and throwing 10,000 of them away. With that ORDER BY on title that also adds on quite a bit of filesorting.

    You would want to utilize an INNER JOIN as such

    SELECT a.title, a.articleid
    FROM articles a
    INNER JOIN (
    SELECT articleid FROM articles
    ORDER BY title LIMIT 10000, 20
    ) AS lim USING(articleid)

    You could even use a range query such as:
    SELECT title FROM articles WHERE position BETWEEN 10000 AND 20 ORDER BY title

    @Chris Southam, I would have to disagree with having to use SQL_CALC_FOUND_ROWS. If your table has an index that can be used COUNT(*) is much faster. Please note this is a COUNT(*) not COUNT(title), there’s a difference.

    ( Reply )
  39. PG

    Ed Baxter February 6th

    Great Stuff :D Thanks alot!

    ( Reply )
  40. PG

    Shaun February 6th

    I fixed my problem, but now I have another! There are 27 records in my database, I have changed the maximum number of records per page to 10, however it is not displaying the other page numbers, only page 1, so my users are not able to look at the other records!

    Does anyone have any idea why this is?!?

    Regards

    Shaun

    ( Reply )
  41. PG

    blues February 6th

    Wonderful Tutorial, thanks.

    ( Reply )
  42. PG

    Bryan P. February 6th

    Wow, what a complete article. Next I am working on a project which needs pagination I will come here

    ( Reply )
  43. PG

    Gastón February 6th

    Excelente, me encantó este tutorial :D

    Sigan así

    Saludos.

    ( Reply )
  44. PG

    sumit February 6th

    any idea on sorting the table?

    ( Reply )
  45. PG

    Ethan February 6th

    Excellent. Will definitely use this.

    ( Reply )
  46. PG

    Phil Tel February 7th

    very good tutorial !!!

    This is the tutorial that i search for a long time…It is rather smiliar to google style pagination. I like that…

    thanks

    ( Reply )
  47. PG

    Bugmenot February 7th

    Has a bug! Click on ALL and then on first page.

    ( Reply )
  48. PG

    Predator7 February 7th

    very good and well explained tutorial

    page bookmarked.

    ( Reply )
  49. PG

    Barry Roodt February 7th

    Good tutorial. You could of course always make use of Zend Paginator : http://framework.zend.com/manual/en/zend.paginator.html – various different options.

    ( Reply )
  50. PG

    Barry Roodt February 7th

    Oh and give the following jQuery plugin a try : http://plugins.jquery.com/project/jqpageflow – provides a different take on pagination.

    ( Reply )
  51. PG

    Aloke Pillai February 7th

    Nice! Really learned the concept!

    ( Reply )
  52. PG

    Bleyder February 7th

    Jason, you are the best. Finally an explained paginator class. Well done!!

    ( Reply )
  53. PG

    Joey February 7th

    I’ve never made a database with enough rows to really consider pagination, but recently I have been considerign starting some personal projects where pagination would be a good idea.

    As mentioned in other articles, doing this in conjunction with AJAX (something I am still a complete newb with) is also a great idea I think

    ( Reply )
  54. PG

    andi February 8th

    thanx a lot

    ( Reply )
  55. PG

    Timo February 8th

    Nice article! I would also like to see how to sort the results too.

    ( Reply )
  56. PG

    dylan February 8th

    My home town, san diego :D

    ( Reply )
  57. PG

    João Pedro Pereira February 8th

    Useful, but the code you have created is very anoying.

    ( Reply )
  58. PG

    Tanax February 9th

    I don’t like the class.
    It outputs data, which a class should never do.

    A class should only process the data. In your index, you should output. What if you wanna change some HTML elements? Or the design of the pagination? You have to enter the class and edit it.

    Nicely written tutorial, but not a good class. Sorry

    ( Reply )
  59. PG

    dario February 9th

    Hi, I´m not an expert using PHP but I want to make this sample on my database, I followed the tuto but it didn´t works, anybody could give me a sample file (index.php) to show the paginator? Thanks

    ( Reply )
  60. PG

    David February 9th

    I just implemented this and it works like a charm. Well done.

    ( Reply )
  61. PG

    jack February 9th

    Great work!! and appreciated.

    ( Reply )
  62. PG

    Zero February 9th

    html in a class? back to 1999!
    MVC anyone??

    oh and btw: http://pear.php.net/package/Pager

    ( Reply )
  63. PG

    Ricky C February 10th

    Nice articles and its well explained but does anyone in here has making this code works properly?

    ( Reply )
  64. PG

    Dado February 10th

  65. PG

    Flex February 10th

    Cool solution! However I attest that iterating through a complete data set each time may be overkill especially on a large dataset (i.e. 100’s of thousands of records). Possible update it using limits based on the pagesize selected.

    Also, I concur with ‘Zero’ that the html belongs outside of that class and should be extracted into templates.

    Overall, nice solution.

    ( Reply )
  66. PG

    123freevectors February 10th

    Great! Instead of jump menu, how get go page search option?

    ( Reply )
  67. PG

    zplits February 11th

    thank you so much for this. Keep em coming. More power

    ( Reply )
  68. PG

    Chris Barton February 11th

    Thank you – it works perfectly on my data and you have cleared a logjam that had me worrying for a long time.

    ( Reply )
  69. PG

    Saorise February 11th

    Great tutorial!

    You also get bonus points from me for pointing out the sample World daatabase that’s available. I really needed that for a project I was working on a couple of months ago – I ended up parsing the CIA World Factbook XML files and extracting the data I needed from there. I could have saved hours!

    ( Reply )
  70. PG

    payam February 11th

    thanks

    ( Reply )
  71. PG

    Saurabh Shah February 12th

    nice tutorial

    ( Reply )
  72. PG

    neron-fx February 12th

    I agree this is a pretty good tutorial but you have definatelty mixed up your view with business logic.

    Would be a pain in the bum to change in terms of styling or adding javascript functions to the links.

    I personally find HTML very hard to read when its emdbedded in PHP. I would have used the class to pass the resultset back to your view and then just loop through the array to create your links in regular XHTML

    ( Reply )
  73. PG

    Tom Cameron February 14th

    I like this tutorial :) . I have had my own pagination class in my toolbox for a while; but I remember struggling with the first versions I used when I wanted to paginate and couldn’t find any tutorials.

    There are a few things that could be simplified even more in your class to speed it up, but a great tutorial all the same! :D

    ( Reply )
  74. PG

    abada February 14th

    nice tutorial

    /*
    anybody could give me a sample file (index.php) to show the paginator?
    */

    me 2 plz

    ( Reply )
  75. PG

    seye kuyinu February 15th

    Nice article…reusable and Object Oriented!!!!!!!!!!!!!!!!!

    ( Reply )
  76. PG

    mk February 15th

    This is a sample index page. it is not the best but works
    items_total = $count;//$num_rows[0];
    $pages->mid_range = 9;
    $pages->paginate();
    echo $pages->display_pages();

    echo “”;
    $query = mysql_query(”SELECT topic_id, topic FROM topics ORDER BY topic_id ASC $pages->limit “);
    while($row = mysql_fetch_array($query) )
    {
    echo $row['topic_id']. ” – “.$row['topic'].”";
    }

    ?>

    ( Reply )
  77. PG

    abaad February 16th

    thanks MK
    but there is an error

    Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘-25,25′ at line 1.

    ( Reply )
  78. PG

    site tracker February 16th

    good stuff..thanks!

    ( Reply )
  79. PG

    Matt February 17th

    How can I change the LIMIT function in the SELECT statement so that it will work with MSSQL databases?

    As far as I can see, if I can find an alternative statement I can get it work properly.

    ( Reply )
  80. PG

    nick February 17th

    If you’re getting the “Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘-25,25′ at line 1.”, it means that you are not passing the right number of rows to the query.
    Here’s how to debug:
    1- do your “select count(*)…” statement
    2- grab the results $countResult = mysql_fetch_row($num_rows);
    3- print the results echo “Number of rows: “.$countResult[0];
    4- if this number is 0 or you get an error then your count statement is messed up. if this number is NOT 0, then make sure this line $pages->items_total = $countResult[0]; is getting the right variable name.

    ( Reply )
  81. PG

    Baby February 17th

    please say what used this class

    please HELPPPPPPPPpp

    please sample running class

    thx

    ( Reply )
  82. PG

    Gianluca February 18th

    Great, thanks to all for the support!

    ( Reply )
  83. PG

    dye February 18th

    wow good! thanks for sharing!

    ( Reply )
  84. PG

    arma9 February 21st

    great article thx

    ( Reply )
  85. PG

    inkubis February 22nd

    wew…

    nice article

    ( Reply )
  86. PG

    soufiane February 23rd

    Thank you ! Great Article :D

    ( Reply )
  87. PG

    Jack March 3rd

    Hello,

    Sorry, I do not speak English, the Google translator who speaks English to me.

    I can not display the Paginator : echo $pages->display_pages();
    Notice: Undefined variable: pages in http://www.tests-org\Pagination\test.php on line 149
    Fatal error: Call to a member function display_pages() on a non-object in http://www.tests-org\Pagination\test.php on line 149

    Here is my code:
    query($sql) as $row)

    if (($items_total = $row[0]) == 0) {
    echo ‘Aucun Item trouvé.‘;
    }
    else {
    if (!isset($_GET['page'])) $_GET['page'] = 0;

    $sql = ‘SELECT * FROM country ORDER BY Code ASC limit ‘.$_GET['page'].’,’.$items_per_page;
    foreach ($dbh->query($sql) as $row)
    {
    print $row['Code'].’ – ‘.$row['Name'].’ – ‘.$row['Continent'].’ – ‘.$row['Region'].’ – ‘.$row['SurfaceArea'].’ – ‘.$row['IndepYear'].’ – ‘.$row['Population'].’ – ‘.$row['LifeExpectancy'].’ – ‘.$row['GNP'].’ – ‘.$row['GNPOld'].’ – ‘.$row['LocalName'].’ – ‘.$row['GovernmentForm'].’ – ‘.$row['HeadOfState'].’ – ‘.$row['Capital'].’ – ‘.$row['Code2'].”;
    }

    }
    $dbh = null;
    }
    catch(PDOException $e)
    {
    echo $e->getMessage();
    }
    ?>

    I tried like this:

    <?php
    $Paginator = paginate($items_total, $items_per_page, $_GET['page'], ‘5′, ‘index.php’);
    echo ‘‘.$Paginator.’‘;
    echo $pages->paginate();
    ?>

    And

    <?php
    $Paginator = paginate($items_total, $items_per_page, $_GET['page'], ‘5′, ‘index.php’);
    echo ‘‘.$Paginator.’‘;
    ?>

    Thank you for telling me where I made a mistake.

    Jeff

    ( Reply )
  88. PG

    Jack March 3rd

    Hello,

    Sorry, I do not speak English, the Google translator who speaks English to me.

    I can not display the Paginator : echo $pages->display_pages();
    Notice: Undefined variable: pages in http://www.tests-org\Pagination\test.php on line 149
    Fatal error: Call to a member function display_pages() on a non-object in http://www.tests-org\Pagination\test.php on line 149

    Here is my code:
    query($sql) as $row)

    if (($items_total = $row[0]) == 0) {
    echo ‘Aucun Item trouvé.‘;
    }
    else {
    if (!isset($_GET['page'])) $_GET['page'] = 0;

    $sql = ‘SELECT * FROM country ORDER BY Code ASC limit ‘.$_GET['page'].’,’.$items_per_page;
    foreach ($dbh->query($sql) as $row)
    {
    print $row['Code'].’ – ‘.$row['Name'].’ – ‘.$row['Continent'].’ – ‘.$row['Region'].’ – ‘.$row['SurfaceArea'].’ – ‘.$row['IndepYear'].’ – ‘.$row['Population'].’ – ‘.$row['LifeExpectancy'].’ – ‘.$row['GNP'].’ – ‘.$row['GNPOld'].’ – ‘.$row['LocalName'].’ – ‘.$row['GovernmentForm'].’ – ‘.$row['HeadOfState'].’ – ‘.$row['Capital'].’ – ‘.$row['Code2'].”;
    }

    }
    $dbh = null;
    }
    catch(PDOException $e)
    {
    echo $e->getMessage();
    }
    ?>

    I tried like this:

    paginate();
    ?>

    And

    <?php
    $Paginator = paginate($items_total, $items_per_page, $_GET['page'], ‘5′, ‘index.php’);
    echo ‘‘.$Paginator.’‘;
    ?>

    Thank you for telling me where I made a mistake.

    Jack

    ( Reply )
  89. PG

    Jaluz March 8th

    Good evening and I excuse – but I do not speak English
    I like vrote class php, but I have a great deal of the evil in creer my index.php file.
    You would have a complete example of a file index.php to exploit (run) this class In his totalite.
    Thank you infinitely for your help (assistant)
    A help would be really useful for me.

    ( Reply )
  90. PG

    joell lapitan March 9th

    i also need a sample of index.php

    my work does not display dynamic SQL..

    huhu.. please help..

    ( Reply )
  91. PG

    Mackenzie March 9th

    This tutorial is a good starting point to understand pagination, but (as many others said) it’s not the best option in terms of perfomance. You can achieve better perfomance (and less code) using limited queries or inner joins with a little bit of Javascript.

    And speaking about object orientation, I’d like to make some tiny suggestions:

    - Declare your variables as private.
    - $default_ipp should be static.
    - $return is not a nice name for a variable.
    - You shouldn’t generate HTML tags from PHP. Delegate the styling!

    ( Reply )
  92. PG

    demon_kyo March 12th

    Thank. Great info.

    ( Reply )
  93. PG

    newbie March 13th

    I’m new to this. Could someone show an example of the index page?

    ( Reply )
  94. PG

    Dj March 16th

    If you have a small number of records .. you can try this tutorial as well.
    http://www.sitepoint.com/article/perfect-php-pagination/

    It is very easy to setup. It also allows you to append other parameters in query string. For example, if you have articles page for author =1 then then page url may look like www example com/articles.php?author = 1
    so for paginated links you may want to retain author id in the query string to keep the result relevant to author 1 .. something ilke
    www example com/articles.php?author = 1& page=2

    ( Reply )
  95. PG

    Williams Alvis March 16th

    excelente tutorial, lo implemento asi:
    addCon(”localhost”, “walcas”, “williams”);
    $pages->addSql(”world”, $sql);
    $pages->paginate();
    echo $pages->display_pages();
    echo ” “. $pages->display_jump_menu() . $pages->display_items_per_page() . “”;
    echo “Page $pages->current_page of $pages->num_pages”;

    // mostrar contenido
    // —————–

    $resultado=$pages->getData();
    while ($row = mysql_fetch_array($resultado, MYSQL_BOTH)) {
    printf(”");
    printf(”ID: %s Name: %s”, $row["ID"], $row["Name"]);
    }

    ?>

    a la clase le agregue dos metodos para el calculo del total de registros, de esta forma no necesito hacer las conexxiones manualmente y otro para que devuelva resultados a mostrar.

    var $sql;
    var $sqlNew;
    var $conn;
    var $dbase;
    function addCon($DBsrv, $DBuser, $DBpwd){
    // establecemos la conexion
    $this->conn = (mysql_connect($DBsrv, $DBuser, $DBpwd)) or die(mysql_error());
    }
    function addSql($DBname, $query){
    $this->dbase = $DBname;
    $this->sql = $query;

    // seleccionamos la Base de Datos
    mysql_select_db($this->dbase, $this->conn);
    $result = mysql_query($this->sql, $this->conn);
    // calcular total de registros
    $this->items_total = mysql_num_rows($result);
    // liberar memoria
    mysql_free_result($result);
    }
    function getData(){
    $this->sqlNew = $this->sql.” “.$this->limit;
    mysql_select_db($this->dbase, $this->conn);
    $result = mysql_query($this->sqlNew, $this->conn);

    return $result;
    }

    ( Reply )
  96. PG

    Williams Alvis March 16th

    addCon(”localhost”, “walcas”, “williams”);
    $pages->addSql(”world”, $sql);
    $pages->paginate();
    echo $pages->display_pages();
    echo ” “. $pages->display_jump_menu() . $pages->display_items_per_page() . “”;
    echo “Page $pages->current_page of $pages->num_pages”;

    // mostrar contenido
    // —————–

    $resultado=$pages->getData();
    while ($row = mysql_fetch_array($resultado, MYSQL_BOTH)) {
    printf(”");
    printf(”ID: %s Name: %s”, $row["ID"], $row["Name"]);
    }

    ?>

    ( Reply )
  97. PG

    Williams Alvis March 16th

    include_once “paginator.class2.php”;
    $sql = “SELECT * FROM city”;

    $pages = new Paginator;
    $pages->addCon(”localhost”, “walcas”, “williams”);
    $pages->addSql(”world”, $sql);
    $pages->paginate();
    echo $pages->display_pages();
    echo ” “. $pages->display_jump_menu() . $pages->display_items_per_page() . “”;
    echo “Page $pages->current_page of $pages->num_pages”;

    // mostrar contenido
    // —————–

    $resultado=$pages->getData();
    while ($row = mysql_fetch_array($resultado, MYSQL_BOTH)) {
    printf(”");
    printf(”ID: %s Name: %s”, $row["ID"], $row["Name"]);
    }

    ( Reply )
  98. PG

    Master2222 March 16th

    Nice article and example, i have to join to needers of index.php, because my code doesn´t work.

    ( Reply )
  99. PG

    Junaid Attari March 27th

    Oh That’s Great!

    ( Reply )
  100. PG

    anyulled April 1st

    good tutorial, but i would like to have a sample on index.php. Would it be possible?

    ( Reply )
  101. PG

    ylcz April 2nd

    i will read it later

    ( Reply )
  102. PG

    krike April 15th

    thanks for that :D really usefull. currently trying to integrate it into a module I create for a CMS system. But I have a small problem I get the following link:

    http://localhost/Nuke-evo/admin.php?page=3&ipp=2&op=Uploadusers

    “&op=Uploadusers” should go before “page=3….”
    how do I change this?

    ( Reply )
  103. PG

    marvinPH April 15th

    Hmm.. I’m thinking of replacing my paging on my website

    smutty.ej.am

    ( Reply )
  104. PG

    Volcan April 16th

    The coding is great!
    but i think there is a little problem with it.

    The problem being the comments as they are absent. Please comment the code and i think u’ll get the better mark or comment from who ever since your coding is simple and clear

    ( Reply )
  105. PG

    Ja May 5th

    I didn’t understand this article, where is option to download whole code…? A plenty of story and divided in many parts and at the end – zero.
    Dude, you need to put here downloadable example if you wish to call yourself guru for PHP.

    ( Reply )
  106. PG

    CgBaran Tuts May 10th

    Nice tut

    ( Reply )
  107. PG

    mike May 13th

    If we could get a index.php in the source zip it would be great. when i do exactly what you say i do not get the same result. i get an All at the top of every looped item. What am i doing wrong

    ( Reply )
  108. PG

    John May 20th

    Is there any way to call just the next or previous page link from the class?

    ( Reply )
  109. PG

    John May 20th

    I have the next and previous link issue worked out by using

    $nextpage = $pages->current_page+1;
    $prevpage = $pages->current_page-1;

    It seems to me that the page that you are currently on shouldn’t be linked at all, and maybe bold it or give it a different style.

    ( Reply )
  110. PG

    vil May 27th

    Excellent article.
    Thanks

    ( Reply )
  111. PG

    andrew June 1st

    Thanks for the paging class mate. After a bit of tweaking here and there in my existing web application functions and was able to get it to work nicely. Cheers!

    ( Reply )
  112. PG

    5s611e June 11th

    dsfsdfs67877 test test

    ( Reply )
  113. PG

    Andrei June 12th

    where can I see a full example because I can’t manage to make it working

    ( Reply )
  114. PG

    TRA June 13th

    Can someone provide index.php to have a complete example?

    Thanx!

    ( Reply )
  115. PG

    squiddy July 6th

    Has anyone (aside from Jason) been successful in getting this tutorial to work.
    It looks to me it is missing some very important parts. In this case, it looks like Jason is missing too.

    ( Reply )
  116. PG

    Elite July 13th

    He explains the usage in the tutorial, why would you need to see how to use it when he shows you?

    What is missing? I made my own database, pulled the content, and used the page-> limit method to limit the SQL call and BOOM, pagination.

    ( Reply )
  117. PG

    Imtiaz Ahmed July 16th

    Nice work, but I need a working example (index.php) to use this class.
    Kindly upload this Class with a complete example. Thanks

    ( Reply )
  118. PG

    Serverman July 21st

    For people asking for a sample index.php file. Here is one you can use. Let me know if it works for you.

    ENJOY!

    limit”;
    $qry1 = mysql_query($check) or die (”Could not match data because “.mysql_error());
    $num_rows = mysql_num_rows($qry1);

    $pages = new Paginator;
    $pages->items_total = $num_rows[0];
    $pages->paginate();
    echo $pages->display_pages();
    echo ” “. $pages->display_jump_menu() . $pages->display_items_per_page() . “”;
    echo “Page $pages->current_page of $pages->num_pages”;

    while($row = mysql_fetch_array($qry1)){

    $firstname = $row['firstname'];
    $lastname = $row['lastname'];
    $company = $row['comapny'];
    echo “”;
    echo ” $firstname”;
    echo ” $lastname”;
    echo ” $company”;
    echo “”;

    }

    ?>

    ( Reply )
  119. PG

    Serverman July 21st

    Sorry, here it is again.

    limit”;
    $qry1 = mysql_query($check) or die (”Could not match data because “.mysql_error());
    $num_rows = mysql_num_rows($qry1);

    $pages = new Paginator;
    $pages->items_total = $num_rows[0];
    $pages->paginate();
    echo $pages->display_pages();
    echo ” “. $pages->display_jump_menu() . $pages->display_items_per_page() . “”;
    echo “Page $pages->current_page of $pages->num_pages”;

    while($row = mysql_fetch_array($qry1)){

    $firstname = $row['firstname'];
    $lastname = $row['lastname'];
    $company = $row['comapny'];
    echo “”;
    echo ” $firstname”;
    echo ” $lastname”;
    echo ” $company”;
    echo “”;

    }

    ?>

    ( Reply )
  120. PG

    AndieR July 25th

    Amazing class! Love it really… had a problem with the Previous and Next not showing up so I looked through the source and on line 59 the 10 should be replaced by a 1 I think. Worked fine then :) Wonder what it would take to get the current page to no longer be a link in the menu.

    line59 if($this->num_pages > 1)

    ( Reply )
  121. PG

    xiao php August 3rd

    This site never disappointed me. Though there are so many php pagination tutorials out there, but I would say this is the best I’ve found so far. I really like this site very much. Maybe I should donate $100 million to this site. Thank you very much……

    php(T_T).\m/ -> php rocksssssss

    ( Reply )
  122. PG

    enatom August 4th

    awful tutorial, he doesnt even show us how to use it on an index.php

    can someone please show a index.php correctly.

    ( Reply )
    1. PG

      JimmyJames September 3rd

      youre an idiot

      ( Reply )
  123. PG

    andy August 11th

    great tutorial, indeed. but it seems the index.php part is missing and the URLs of examples are broken. here is the part of my index.php that related to pagination. there are two things that need consideration, the first would be the situation when numebr of rows = 0 or $result is false. another one is $string variable, “$pages->limit” should be added at the end of the second $string variable.

    0)
    {
    $pages = new Paginator;
    $pages->items_total = $num_rows;
    $pages->paginate();
    echo $pages->display_pages();
    echo $pages->display_items_per_page();
    }
    else
    {
    echo “nothing here”;
    }

    echo “”;
    $string = $string.”$pages->limit”;
    $query = mysql_query($string) or die (mysql_error());
    $result = mysql_fetch_array($query);
    if($result==true)
    {
    do
    {
    // code for displaying items
    }while($result = mysql_fetch_array($query));
    }
    echo “”;
    if($num_rows>0)
    {
    echo $pages->display_pages().$pages->display_items_per_page();
    }
    ?>

    Here is my blog http://blog.growthsys.com/?p=210

    The demo of above code http://www.growthsys.com/examples/pagination/pagination.php

    here to download code http://www.growthsys.com/examples/pagination/pagination.zip

    ENJOY!

    ( Reply )
    1. PG

      John October 21st

      Thanks! This has helped me loads getting it to work.

      ( Reply )
  124. PG

    andy August 11th

    strange, code could not be uploaded completely:

    here i am trying again

    $string = “select * from brands order by id”;
    $query = mysql_query($string) or die (mysql_error());
    $num_rows = mysql_num_rows($query);
    if($num_rows>0)
    {
    $pages = new Paginator;
    $pages->items_total = $num_rows;
    $pages->paginate();
    echo $pages->display_pages();
    echo $pages->display_items_per_page();
    }
    else
    {
    echo “nothing here”;
    }

    echo “”;
    $string = $string.”$pages->limit”;
    $query = mysql_query($string) or die (mysql_error());
    $result = mysql_fetch_array($query);
    if($result==true)
    {
    do
    {
    // code for displaying items
    }while($result = mysql_fetch_array($query));
    }
    echo “”;
    if($num_rows>0)
    {
    echo $pages->display_pages().$pages->display_items_per_page();
    }

    ( Reply )
  125. PG

    Kasper August 18th

    Rather nice tut but I am really missing some solid examples of how to use it. To me it dosent seem that anything is parsed into the pagination class which makes me wonder on how it should work at all?

    Regards

    ( Reply )
    1. PG

      JimmyJames September 3rd

      check the website that developed it (catchmyfame.com) for examples. they have a few there plus a sample db.

      ( Reply )
  126. PG

    Manilyn Mendoza Abne August 18th

    can you give me one example of damath and its solution for my project. pls

    ( Reply )
  127. PG

    Rohan August 30th

    Brilliant!!! Thanks so much!

    ( Reply )
  128. PG

    Benito October 1st

    Hi

    I’m having trouble getting this to work. I’m sure its obvious but I’ve been staring at this screen too long now….

    When I paste the code in and run the page all I get is

    All Page: Items per page:

    Page 0 of 0

    I get this even though my page returns the required results. It’s just not paginating anything!!!

    Please help!!!!!!

    ( Reply )
  129. PG

    laiq October 5th

    Dear All :

    I notice all comments example use mysql database.

    Can I use this class with ODBC ?

    and if is possible please see me sample code how I use.

    Thanks a lot.

    ( Reply )
  130. PG

    David Moreen November 13th

    At first I thought this sucked because I had idea how to implement it. So I then navigated to catchmyfame.com and was able to download a zip containing examples. Now I couldn’t be happier!

    – Weird doesn’t that sound like an infomercial pitch?

    ( Reply )
  1. Arrow
    Gravatar

    Your Name
    November 13th