Skip to content

Instantly share code, notes, and snippets.

@sptrsn
Last active February 9, 2017 14:39
Show Gist options
  • Save sptrsn/0740d55734031143a851574b5894ee74 to your computer and use it in GitHub Desktop.
Save sptrsn/0740d55734031143a851574b5894ee74 to your computer and use it in GitHub Desktop.
pagination class
class pager{
/*
$pager = new pager;
$pager->paginate(400);
*/
private $limit = 5;
private $offset;
private $row_count;
private $page_count;
private $cur_page;
private $getvar = 'p';
private $range = 3;
public function paginate($row_count=null,$limit=null){
if(!is_null($limit))$this->limit = $limit;
$this->row_count = isset($row_count) ? $row_count : 1;
$base_url = $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
$this->link = 'http://'.$base_url.'?'.$this->getvar.'=%d';
$this->page_count = ceil($this->row_count/$this->limit);
$pg = isset($_GET[$this->getvar]) ? $_GET[$this->getvar] : 1;
$this->cur_page = preg_replace('/[^0-9]/','',$pg);
switch(TRUE){
case empty($this->cur_page):
$this->cur_page = 1;
break;
case $this->cur_page < 1:
$this->cur_page = 1;
break;
case $this->cur_page > $this->page_count:
$this->cur_page = $this->page_count;
break;
}
$this->offset = $this->cur_page * $this->limit;
$current_range = [($this->cur_page - $this->range < 1 ? 1 : $this->cur_page - $this->range),($this->cur_page + $this->range > $this->page_count ? $this->page_count : $this->cur_page + $this->range)];
$first_page = $this->cur_page > 3 ? '<a href="'.sprintf($this->link, '1').'">1</a>'.($this->cur_page < 5 ? ', ' : ' ... ') : null;
$last_page = $this->cur_page < $this->page_count-2 ? ($this->cur_page > $this->page_count-4 ? ', ' : ' ... ').'<a href="'.sprintf($this->link, $this->page_count).'">'.$this->page_count.'</a>' : null;
$previous_page = $this->cur_page > 1 ? '<a href="'.sprintf($this->link, ($this->cur_page-1)).'">Previous </a>' : null;
$next_page = $this->cur_page < $this->page_count ? '<a href="'.sprintf($this->link, ($this->cur_page+1)).'"> Next </a>' : null;
for($x=$current_range[0];$x <= $current_range[1]; ++$x){
$pages[] = '<a href="'.sprintf($this->link, $x).'">'.($x == $this->cur_page ? '<strong>'.$x.'</strong>' : $x).'</a>';
}
if($this->page_count > 1){
echo '<div class="paginate">'.$previous_page.$first_page.implode(', ', $pages).$last_page.$next_page.'</div>';
}
$this->vars();
}
public function vars(){
pr('Limit: '.$this->limit);
pr('Offset: '.$this->offset);
pr('Current Page: '.$this->cur_page);
pr('Total Rows: '.$this->row_count);
pr('Total Pages: '.$this->page_count);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment