php 简单分页类
写这个分页类主要是用来理解php的分页原理
<?php
/**
* 分页类
* 真分页是每次都去数据库查询,增加数据库的负担
* 假分页是第一次查询,然后读取数据,没有及时性
*/
class pagination {
private $total; //总记录数
private $pagesize; //每页显示多少条
private $limit; //每页显示条数
private $url; //自定义url
private $page; //当前页码
private $pagenum; //总页码
//构造方法
public function __construct($count,$size) {
$this->total = $count ? $count : 1;
$this->pagesize = $size;
$this->pagenum = ceil($this->total/$this->pagesize);
$this->page = $this->getPage();
$this->url = $this->getUrl();
}
private function getPage() {
$page = !empty($_GET['page']) ? $_GET['page'] : 1;
$page = ($page > 0) ? $page : 1;
if($page > $this->pagenum) {
return $this->pagenum;
} else {
return $page;
}
}
private function getUrl() {
$url = $_SERVER['REQUEST_URI'];
return $url;
}
private function replaceUrl($page) {
//解析url
$param = parse_url($this->url);
if(isset($param['query'])) {
$route = preg_replace('/page=(\d+)/', 'page='.$page, $this->url);
} else {
if($page >= 1) {
$route = $this->url.'?page='.$page;
} else {
$route = $this->url;
}
}
return $route;
}
//首页|第一页
private function first() {
if($this->page != 1) {
return '<a href="'.$this->replaceUrl(1).'">首页</a>';
} else {
return '<span>首页</span>';
}
}
//上一页
private function prev() {
if($this->page == 1) {
return '<span>上一页</span>';
}
return '<a href="'.$this->replaceUrl($this->page-1).'">上一页</a>';
}
//下一页
private function next() {
if($this->page == $this->pagenum) {
return '<span>下一页</span>';
}
return '<a href="'.$this->replaceUrl($this->page+1).'">下一页</a>';
}
//尾页
private function last() {
if($this->page != $this->pagenum) {
return '<a href="'.$this->replaceUrl($this->pagenum).'">尾页</a>';
}
return '<span>尾页</span>';
}
//显示分页信息
public function show() {
header("Content-type: text/html; charset=utf-8");
$str = '<div id="">';
$str .= $this->first();
$str .= $this->prev();
if($this->page > 1) {
$str .= '<span>...</span>';
}
for ($i=1; $i <= $this->pagenum; $i++) {
if($i == $this->page) {
$str .= '<a href="'.$this->replaceUrl($i).'" class="cur">'.$i.'</a>';
} else {
$str .= '<a href="'.$this->replaceUrl($i).'">'.$i.'</a>';
}
}
if($this->page < $this->pagenum) {
$str .= '<span>...</span>';
}
$str .= $this->next();
$str .= $this->last();
return $str;
}
}
$page = new pagination(20,3);
echo $page->show();