Pagination in PHP or Java

I suppose it's inevitable - I pulled my really old Pagination article from this site a while back when I blitzed the site.  I suppose I just considered it a bit old, but it seems people still want to use it.  I do actually still use the code myself - mostly because it's quite generic.  I've also ported it to Java, with a simple tag library, so I'll post them both here in case anyone's interested.

You may be wondering why I bothered to port to Java.  Surely there are loads of pagination examples out there already?  Well yes, but most are tied to a framework like Struts, or use tables for layout, or have some other limitation.  I looked for a while for a better one, but then gave up and ported my code instead - it only took an hour.  So, if it can be of use to others, here's the code.

PHP version

I won't go into the nitty-gritty of what this does behind the scenes, but effectively it provides internal methods to calculate the parameters and the display methods use these.  So, you'd do something like this:

< ?php
require_once("pagination.php");
$pagination = new Paginate($start, $limit, $num, $url, $maxpages);
echo $pagination->displayUL();
?>

The first 3 parameters come from or are used in your DB query:  $start and $limit are just those values you'd use in your MySQL or other DB query to limit the results to what you're actually displaying on the current page.  $num requires a second DB query, to count(*) the number of rows that would be returned without the limit clause.  $url is normally $_SERVER['PHP_SELF'].  $maxpages is just to prevent loads of page links if there is a lot of data to page through.  A value of 20 is normally OK for that.  After that, use CSS to change the display. 

Download the class here.

Java version

To use the java version, you should just be able to put the .tld file in your WEB-INF directory, add the class to your deployment, and use the tag like this:

<%@ taglib uri="http://pagination.ecreate.co.uk" prefix="page"%>
<div class="pagination">
<page:list start="<%=start%>" 
   limit="<%=limit%>"
   num="<%=num%>"
   maxPages="10"
   showNextPrev="true"
   showFirstLast="true"
   showPageNumbers="true"
   url="your/url.html?" /> </div>

Again, just use CSS to modify the way the list is presented.  You can find some good CSS examples here, or look in my source code where you'll find some.

 

 


© eCreate Web Services Limited, 2008