您的位置:首页 > 编程语言 > PHP开发

PHP分页原理+代码实现

2016-05-03 13:47 681 查看

PHP分页原理

Mysql分页查询Limit关键字

sql语句

select * from table_name limit a,b;


limit a,b 代表从第a条数据开始,查询总共b条的数据,用limit就可以轻松实现页面分页,下面是PHP分页类

使用方法

实例化Page类(可以传入两个参数pageSize和maxSize)

调用pageCaclt方法,传入当前页,返回从数据库查询的数组

调用gainLi方法,传入当前页,返回页码显示条,可直接在html中输出该变量。

<?php
class Page{
public $mysqli;
public $totalCount;  //数据总条数
public $pageSize;   //每页显示条数
public $firstPage;  //第一页
public $endPage;    //最后一页
public $maxSize;     //最大显示多少页(大于该数用...代替)
public $currentPage; //当前页
public $pageNum;
public function __construct($pageSize=15,$maxSize=7){
$this->pageSize=$pageSize;
$this->maxSize=$maxSize;
$this->mysqli=new mysqli('localhost','root','tiger','capture');
if($this->mysqli->connect_errno){
echo $this->mysqli->connect_error;
exit;
}
$this->totalCount=$this->getAllCount();
$this->pageNum=ceil($this->totalCount/$pageSize);
}
public function getAllCount(){
$query="select count(*) from prevideo";
$result=$this->mysqli->query($query);
if($result->num_rows>0){
$data=$result->fetch_array();
$result->close();
return $data[0];
}
return 0;
}
public function pageCaclt($currentPage){
if($currentPage<1||$currentPage>$this->pageNum)
$currentPage=1;
$start=($currentPage-1)*$this->pageSize;
$query="select * from prevideo limit {$start},{$this->pageSize}";
$result=$this->mysqli->query($query);
$data=array();
while($d=$result->fetch_array()){
$data[]=$d;
}
return $data;
}
public function gainLi($currentPage){
if($currentPage<1||$currentPage>$this->pageNum)
$currentPage=1;
$pageLi="";
if($this->pageNum<=$this->maxSize){
$pageLi.="<div style='margin:0 auto;width:800px;height:50px;
text-align:center;'><span>共{$this->pageNum}页</span> ";
for($i=1;$i<$this->pageNum;$i++){
if($i==$currentPage)
$pageLi.="<span style='background:red;'>$i</span>   ";
else
$pageLi.="<span><a href='?page=$i'>$i</a></span>   ";
}
$pageLi.="</div>";
}
else{
$pre=$currentPage>1?$currentPage-1:1;
$next=$currentPage<$this->pageNum?$currentPage+1:$this->pageNum;
$divide=($this->maxSize-1)/2;
$left=$currentPage-$divide;
if($left<1)
$left=1;
if($left+$this->maxSize>=$this->pageNum)
$left=$this->pageNum-$this->maxSize+1;
$right=$left+$this->maxSize-1;
$pageLi.="<div style='margin:0 auto;width:800px;height:50px;
text-align:center;'><span>共{$this->pageNum}页</span> ";
if($currentPage==1){
$pageLi.="<span>首页</span>  ";
$pageLi.="<span>上一页</span>  ";
}
else{
$pageLi.="<span><a href='?page=1'>首页</a></span>  ";
$pageLi.="<span><a href='?page={$pre}'>上一页</a></span>  ";
}
for($i=$left;$i<=$right;$i++){
if($i==$currentPage)
$pageLi.="<span style='background:red;'>$i</span>  ";
else
$pageLi.="<span><a href='?page=$i'>$i</a></span>  ";
}
if($currentPage==$this->pageNum){
$pageLi.="<span>下一页</span>  ";
$pageLi.="<span>尾页</span>";
}
else{
$pageLi.="<span><a href='?page={$next}'>下一页</a></span>  ";
$pageLi.="<span><a href='?page={$this->pageNum}'>尾页</a></span>";
}
$pageLi.="</div>";
}
return $pageLi;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: