Simple Pagination

I use alot of Zend Framework for my freelance projects and prior to version 1.6 they have no pagination class to do the dirty work. I know what you’re thinking right now, why didn’t I just reused some of the many pagination scripts in the internet and/or in PEAR. I just really needed something simple that I can quickly reuse all over my web-app and here it is

To get the offset for your sql query just do this:

$offset = $numOfItemsPerPage * ($page - 1);

Here’s the code for the pagination, take note that the logic can be use regardless of the programming language, i’ve also use this in some of my java webapps

<?php
class Paginator {
	const NUM_TRAIL_LEAD_LINKS = 5;

	public static function generate($url, $total, $current = 1, $numPerPage = 5, $var = 'page', $separator = ' ') {
		$totalNumberOfPages = ceil($total / $numPerPage);

		$linksArray = array();
		$isFirstLinkDone = false;
		$i = 1;
		if(($current - self::NUM_TRAIL_LEAD_LINKS) > $i) {
			$i = $current - self::NUM_TRAIL_LEAD_LINKS;
		}

		for(;$i<=$totalNumberOfPages;$i++) {
			if(!$isFirstLinkDone && $current > 1) {
				$linksArray[] = '<a href="'.$url.'/'.$var.'/1">First</a>';
				$linksArray[] = '<a href="'.$url.'/'.$var.'/'.($current-1).'">Prev</a>';
				$isFirstLinkDone = true;
			}

			if($i == $current) {
				$linksArray[] = '<span style="font-weight:bold">'.$current.'</span>';
			}
			else {
				if(($current + self::NUM_TRAIL_LEAD_LINKS) < $i) {
					break;
				}

				$linksArray[] = '<a href="'.$url.'/'.$var.'/'.$i.'">'.$i.'</a>';
			}
		}

		if($current < $totalNumberOfPages) {
			$linksArray[] = '<a href="'.$url.'/'.$var.'/'.($current+1).'">Next</a>';
			$linksArray[] = '<a href="'.$url.'/'.$var.'/'.$totalNumberOfPages.'">Last</a>';
		}
		return implode($separator, $linksArray);
	}
}
This entry was posted in Uncategorized. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

2 Comments

  1. Michael Murray
    Posted September 27, 2008 at 9:08 pm | Permalink

    I believe your server-side script (perhaps WordPress) is munging your code.

    & turned into &amp;amp; for example. There are also some omissions in your code.

  2. Posted September 27, 2008 at 9:21 pm | Permalink

    @Michael Murray
    Thanks for pointing that out, this is the first time i’ve tried posting code snippets.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*