一个很简单的PHP分页类
2012-1-30 11:29 Monday  

分类: PHP 评论(53) 浏览(29533)

花了大半个上午,就整出这个东西

<?php
/**
* @what 分页类
* @author Aboc QQ:9986584
* @version 1.0
* @date 2008-8-31
*/

class page{
var $page_name='page'; //数据名称
var $page_size; //每页条数
var $db;//数据操作对象
var $page_num;//总页数
var $page=0; //当前页码
var $num; //数据总条数

/**
* Enter 取得分页数据
*
* @param unknown_type $sql
* @param unknown_type $db
* @param unknown_type $page_size
* @return array;
*/
function getData($sql,$db,$page_size=20){
   $this->page_size=$page_size;
   if(strripos($sql,'limit') != false)die('SQL中不可出现limit');
   if($page_size<=0)die('$page_size设置错误');
   $sql=trim($sql);
   $this->num=$db->getnum($sql);
   if($this->num<=$page_size){
    $this->page_num=0;
   }else{
    $this->page_num=ceil($this->num/$page_size)-1;
   }
   if(empty($_GET[$this->page_name]) || $_GET[$this->page_name] <0 ){
    $this->page=0;
   }elseif($_GET[$this->page_name] > $this->page_num){
    $this->page=$this->page_num;
   }else{
    $this->page=$_GET[$this->page_name];
   }
   $sql.=' limit '.($this->page*$page_size).','.$page_size;
   $row=$db->getall($sql);
   //echo $sql;
   return $row;  
}

/**
* 返回去除$page_name之后的查询字串
*
* @return unknown
*/
function getquery(){
   $query=$_SERVER['QUERY_STRING'];
   //echo $query;
   //echo $this->page_name;
   //echo strripos($query,$this->page_name);
   //echo strpos($query,$this->page_name);
   if(empty($query)) return false;
   if(($end=strpos($query,$this->page_name)) !== false){
    if($end==0) $end=1;
    $query=substr($query,0,$end-1);
   }
   //echo $query;
   return $query;
}

/**
* 输出分页链接
*
* @return unknown
*/
function pagelist(){
   $query=$this->getquery();
   if(empty($query)){
    $query='';
   }else{
    $query=$query.'&';
   }
   $total='总共'.$this->num.'条 每页'.$this->page_size.'条';
   $startpage='<a href="?'.$query.$this->page_name.'=0">首页</a>';
   $endpage='<a href="?'.$query.$this->page_name.'='.$this->page_num.'">尾页</a>';
   if($this->page==0){
    $prepage='上一页';
   }else{
    $prepage='<a href="?'.$query.$this->page_name.'='.($this->page-1).'">上一页</a>';
   }
   if($this->page==$this->page_num){
    $nextpage='下一页';
   }else{
    $nextpage='<a href="?'.$query.$this->page_name.'='.($this->page+1).'">下一页</a>';
   }
   return $total.' '.$startpage.' '.$prepage.' '.$nextpage.' '.$endpage;
}
  
}
?>

演示就是下面这个样子的

+1 19

留下你的看法: