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