PHP Tutorial : Results Pagination

Among the most common tasks for a php CMS writer is to handle pagination.

Pagination is needed when there are many entries in the database and they can not be shown in a single page of results. A pagination navigation bar gives the user the ability to see a smaller list of entries.

Pagination is not as easy as it seems, expecially when dealing with seo friendly urls or multi language sites. However here’s a solution for pagination in php. Simple and up to the point:

First, we calculate the total amount of entries. Then the numbers of pages needed to show everthing. And, of course, we need to know how many results are to be displayed per page. Finally, we’ll print out the entries and links for next, previous and each individual page number.

MySql LIMIT clause accepts either one or two values. In this example we use two so it returns values between -say- 10 and 20. If you only use one value, as in LIMIT 10, it will return the first 10 results.

The second value is a quantity, not an index!
In other words, don’t do LIMIT 0,10 then LIMIT 10,20 then LIMIT 20,30: it won’t work. Instead, use LIMIT 0,10, LIMIT 10,10, LIMIT 20,10.

<?php
//include database connection (check previous posts to get this one)
>include('dbConnection.php');
//get the number of total rows
$query = "SELECT * FROM TableName";
$result = mysql_query($query);
// Number of records found
$num_record = mysql_num_rows($result);
// Number of results per page
$display = 5;

if(isset($_GET['page'])) {
$currentPage = $_GET['page'];
}else{
$currentPage = 1;
}
//last page - we use ceil because page range is 1 to Max, this way page "2.5" becomes page 3
$lastPage = ceil($num_record/$display);
//limit in the query thing
$limitQ = 'LIMIT ' .($currentPage - 1) * $display .',' .$display;
//normal query and print results
$query = "SELECT * FROM TableName $limitQ";
$result = mysql_query($query);
//here you do your loop like
>while($row=@mysql_fetch_object($result)) {

print "$row->FieldName";
}
//pagination navigation (links)

//previous
>if ($currentPage == 1) {

print "Prev ";
} else {

print "<a href=pagename.php?page=1>First page</a> ";
$previousPage = $currentPage-1;

print "<a href=pagename.php?page=$previousPage>Previous</a>";
}

print " { Page $currentPage of $lastPage } ";
//for next pages links
>if ($currentPage== $lastPage) {

print "Next last";
} else {
$nextPage = $currentPage+1;

print " <a href=pagename.php?page=$nextPage>NEXT</a> ";

print " <a href=pagename.php?page=$lastPage>LAST</a> ";
}
?>

Now you can use this pagination to split your mysql results into multiple webpages, but there are better ways to handle this problem, as we’ll see in the future: keep in mind that right now we are reading all values every time, and this may burden our script. A better way would be to pre-count the number of results and then select only those we are going to show.

Also, for something like a comment page, an ajax pagination approach would probably be better. Again, we’ll get back at this in another tutorial -as always drop a comment if there is something you’d like to see explained more in depth.

5 Responses to “PHP Tutorial : Results Pagination”

  1. XkiD | PHP Tutorial : Results Pagination | blog.xkid.ro Says:

    [...] the original post here:  PHP Tutorial : Results Pagination Posted in PHP | Tags: database, image-below, name-on-every, page-numbers-, PHP, [...]


  2. Roy Says:

    Greetings,
    there is a missing ) on the isset line. Thanks for the tutorial but clicking on next or last doesn’t display anything. I tried using self instead of pagename and got error messages. How do I get the pages beyond page one to display the data?


  3. admin Says:

    Thanks for pointing out the missing parenthesis (now fixed), there are also some extra greater than signs before control statements. I have to look at the plugin that formats the code, as it seems not to work properly.

    I had a look at the code, and it should work. Try removing the @ sign in front of the mysql fetch function, and see if an error arises. Will have a deeper look at the code and report back.


  4. igwe Says:

    This is the error I am getting

    Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in C:\Program Files\xampp\htdocs\phpfiles\pagination.php on line 16

    viewing 1 – of entries
    pages:

    Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in C:\Program Files\xampp\htdocs\phpfiles\pagination.php on line 57

    please any help will be appreciated.


  5. admin Says:

    These errors means that the query was not successful. The code snippet in this post does not make any error checking and even suppresses some errors. Are you sure the MySQL DB is properly setup?

    You may want to try to type the same query in MyPHPadmin and rule out any MySQL problem. Also, remove the @ sign in the code. This will let PHP to output the errors as they happen and provide you with more insight in the problem.


Leave a Reply

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