作者:夜猫子([email protected])
1、前言
分页显示是一种非常常见的浏览和显示大量数据的方法,属于web编程中最常处理的事件之一。对于web编程的老手来说,编写这种代码实在是和呼吸一样自然,但是对于初学者来说,常常对这个问题摸不着头绪,因此特地撰写此文对这个问题进行详细的讲解,力求让看完这篇文章的朋友在看完以后对于分页显示的原理和实现方法有所了解。本文适合初学者阅读,所有示例代码均使用php编写。
2、原理
所谓分页显示,也就是将数据库中的结果集人为的分成一段一段的来显示,这里需要两个初始的参数:
每页多少条记录($pagesize)?
当前是第几页($currentpageid)?
现在只要再给我一个结果集,我就可以显示某段特定的结果出来。
至于其他的参数,比如:上一页($previouspageid)、下一页($nextpageid)、总页数($numpages)等等,都可以根据前边这几个东西得到。
以mysql数据库为例,如果要从表内截取某段内容,sql语句可以用:select * from table limit offset, rows。看看下面一组sql语句,尝试一下发现其中的规率。
前10条记录:select * from table limit 0,10
第11至20条记录:select * from table limit 10,10
第21至30条记录:select * from table limit 20,10
……
这一组sql语句其实就是当$pagesize=10的时候取表内每一页数据的sql语句,我们可以总结出这样一个模板:
select * from table limit ($currentpageid - 1) * $pagesize, $pagesize
拿这个模板代入对应的值和上边那一组sql语句对照一下看看是不是那么回事。搞定了最重要的如何获取数据的问题以后,剩下的就仅仅是传递参数,构造合适的sql语句然后使用php从数据库内获取数据并显示了。以下我将用具体代码加以说明。
3、简单代码
请详细阅读以下代码,自己调试运行一次,最好把它修改一次,加上自己的功能,比如搜索等等。
[code:1:c1661dd3ea]
<?php
// 建立数据库连接
$link = mysql_connect("localhost", "mysql_user", "mysql_password")
or die("could not connect: " . mysql_error());
// 获取当前页数
if( isset($_get['page']) ){
$page = intval( $_get['page'] );
}
else{
$page = 1;
}
// 每页数量
$pagesize = 10;
// 获取总数据量
$sql = "select count(*) as amount from table";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
$amount = $row['amount'];
// 记算总共有多少页
if( $amount ){
if( $amount < $page_size ){ $page_count = 1; } //如果总数据量小于$pagesize,那么只有一页
if( $amount % $page_size ){ //取总数据量除以每页数的余数
$page_count = (int)($amount / $page_size) + 1; //如果有余数,则页数等于总数据量除以每页数的结果取整再加一
}else{
$page_count = $amount / $page_size; //如果没有余数,则页数等于总数据量除以每页数的结果
}
}
else{
$page_count = 0;
}
// 翻页链接
$page_string = '';
if( $page == 1 ){
$page_string .= '第一页|上一页|';
}
else{
$page_string .= '<a href=?page=1>第一页</a>|<a href=?page='.($page-1).'>上一页</a>|';
}
if( ($page == $page_count) || ($page_count == 0) ){
$page_string .= '下一页|尾页';
}
else{
$page_string .= '<a href=?page='.($page+1).'>下一页</a>|<a href=?page='.$page_count.'>尾页</a>';
}
// 获取数据,以二维数组格式返回结果
if( $amount ){
$sql = "select * from table order by id desc limit ". ($page-1)*$page_size .", $page_size";
$result = mysql_query($sql);
while ( $row = mysql_fetch_row($result) ){
$rowset[] = $row;
}
}else{
$rowset = array();
}
// 没有包含显示结果的代码,那不在讨论范围,只要用foreach就可以很简单的用得到的二维数组来显示结果
?>
[/code:1:c1661dd3ea]
4、oo风格代码
以下代码中的数据库连接是使用的pear db类进行处理
[code:1:c1661dd3ea]
<?php
// filename: pager.class.php
// 分页类,这个类仅仅用于处理数据结构,不负责处理显示的工作
class pager
{
var $pagesize; //每页的数量
var $currentpageid; //当前的页数
var $nextpageid; //下一页
var $previouspageid; //上一页
var $numpages; //总页数
var $numitems; //总记录数
var $isfirstpage; //是否第一页
var $islastpage; //是否最后一页
var $sql; //sql查询语句
function pager($option)
{
global $db;
$this->_setoptions($option);
// 总条数
if ( !isset($this->numitems) )
{
$res = $db->query($this->sql);
$this->numitems = $res->numrows();
}
// 总页数
if ( $this->numitems > 0 )
{
$this->numpages = ceil($this->numitems / $this->pagesize);
}
else
{
$this->numpages = 0;
}
switch ( $this->currentpageid )
{
case $this->numpages == 1:
$this->isfirstpage = true;
$this->islastpage = true;
break;
case 1:
$this->isfirstpage = true;
$this->islastpage = false;
break;
case $this->numpages:
$this->isfirstpage = false;
$this->islastpage = true;
break;
default:
$this->isfirstpage = false;
$this->islastpage = false;
}
if ( $this->numpages > 1 )
{
if ( !$this->islastpage ) { $this->nextpageid = $this->currentpageid + 1; }
if ( !$this->isfirstpage ) { $this->previouspageid = $this->currentpageid - 1; }
}
return true;
}
/***
*
* 返回结果集的数据库连接
* 在结果集比较大的时候可以直接使用这个方法获得数据库连接,然后在类之外遍历,这样开销较小
* 如果结果集不是很大,可以直接使用getpagedata的方式获取二维数组格式的结果
* getpagedata方法也是调用本方法来获取结果的
*
***/
function getdatalink()
{
if ( $this->numitems )
{
global $db;
$pageid = $this->currentpageid;
$from = ($pageid - 1)*$this->pagesize;
$count = $this->pagesize;
$link = $db->limitquery($this->sql, $from, $count); //使用pear db::limitquery方法保证数据库兼容性
return $link;
}
else
{
return false;
}
}
/***
*
* 以二维数组的格式返回结果集
*
***/
function getpagedata()
{
if ( $this->numitems )
{
if ( $res = $this->getdatalink() )
{
if ( $res->numrows() )
{
while ( $row = $res->fetchrow() )
{
$result[] = $row;
}
}
else
{
$result = array();
}
return $result;
}
else
{
return false;
}
}
else
{
return false;
}
}
function _setoptions($option)
{
$allow_options = array(
'pagesize',
'currentpageid',
'sql',
'numitems'
);
foreach ( $option as $key => $value )
{
if ( in_array($key, $allow_options) && ($value != null) )
{
$this->$key = $value;
}
}
return true;
}
}
?>
<?php
// filename: test_pager.php
// 这是一段简单的示例代码,前边省略了使用pear db类建立数据库连接的代码
require "pager.class.php";
if ( isset($_get['page']) )
{
$page = (int)$_get['page'];
}
else
{
$page = 1;
}
$sql = "select * from table order by id";
$pager_option = array(
"sql" => $sql,
"pagesize" => 10,
"currentpageid" => $page
);
if ( isset($_get['numitems']) )
{
$pager_option['numitems'] = (int)$_get['numitems'];
}
$pager = @new pager($pager_option);
$data = $pager->getpagedata();
if ( $pager->isfirstpage )
{
$turnover = "首页|上一页|";
}
else
{
$turnover = "<a href='?page=1&numitems=".$pager->numitems."'>首页</a>|<a href='?page=".$pager->previouspageid."&numitems=".$pager->numitems."'>上一页</a>|";
}
if ( $pager->islastpage )
{
$turnover .= "下一页|尾页";
}
else
{
$turnover .= "<a href='?page=".$pager->nextpageid."&numitems=".$pager->numitems."'>下一页</a>|<a href='?page=".$pager->numpages."&numitems=".$pager->numitems."'>尾页</a>";
}
?>
[/code:1:c1661dd3ea]
需要说明的地方有两个:
这个类仅仅处理数据,并不负责处理显示,因为我觉得将数据的处理和结果的显示都放到一个类里边实在是有些勉强。显示的时候情况和要求多变,不如自己根据类给出的结果处理,更好的方法是根据这个pager类继承一个自己的子类来显示不同的分页,比如显示用户分页列表可以:
[code:1:c1661dd3ea]
<?php
class memberpager extends pager
{
function showmemberlist()
{
global $db;
$data = $this->getpagedata();
// 显示结果的代码
// ......
}
}
/// 调用
if ( isset($_get['page']) )
{
$page = (int)$_get['page'];
}
else
{
$page = 1;
}
$sql = "select * from members order by id";
$pager_option = array(
"sql" => $sql,
"pagesize" => 10,
"currentpageid" => $page
);
if ( isset($_get['numitems']) )
{
$pager_option['numitems'] = (int)$_get['numitems'];
}
$pager = @new memberpager($pager_option);
$pager->showmemberlist();
?>
[/code:1:c1661dd3ea]
第二个需要说明的地方就是不同数据库的兼容性,在不同的数据库里截获一段结果的写法是不一样的。
mysql: select * from table limit offset, rows
pgsql: select * from table limit m offset n
......
所以要在类里边获取结果的时候需要使用pear db类的limitquery方法。
ok,写完收功,希望花时间看完这些文字的你不觉得是浪费了时间。
【发表回复】【查看论坛原帖】【添加到收藏夹】【关闭】
--------------------------------------------------------------------------------
tonera 回复于:2003-10-16 12:14:48
加精华,这里的精华也太少了点。 :lol:
--------------------------------------------------------------------------------
i_just_shot_john_lennon 回复于:2003-10-22 14:54:15
感谢夜猫子老大能把这么好的代码共享出来
刚好做一个分页的小程序,用的也是pear的db库
所以就想用上这段代码了
不过发现有个小地方需要改进一下
[code:1:1dff2b643d]
// 总条数
if ( !isset($this->numitems) )
{
$res = $db->query($this->sql);
$this->numitems = $res->numrows();
}
[/code:1:1dff2b643d]
就是再查询总条数的
用
select count(*) from table
比
select * from table来数条数应该效率上会好一些吧
对于数据量很大的数据表来说
--------------------------------------------------------------------------------
夜猫子 回复于:2003-10-22 15:04:52
是的,关于查询总条数的确有这个问题,不过完全可以用其他方式来搞定。
首先,如果采用select count(*) from table的话,我们就需要多传递一条sql语句,这可能使程序的可读性降低。
第二,其实在第一次调用以后,我们都可以把$pager->numitems这个总记录数通过翻页的那个链接传递给下一次。
[code:1:3262bf44d3]
if ( $pager->isfirstpage )
{
$turnover = "首页|上一页|";
}
else
{
$turnover = "<a href='?page=1&numitems=".$pager->numitems."'>首页</a>|<a href='?page=".$pager->previouspageid."&numitems=".$pager->numitems."'>上一页</a>|";
}
if ( $pager->islastpage )
{
$turnover .= "下一页|尾页";
}
else
{
$turnover .= "<a href='?page=".$pager->nextpageid."&numitems=".$pager->numitems."'>下一页</a>|<a href='?page=".$pager->numpages."&numitems=".$pager->numitems."'>尾页</a>";
}
[/code:1:3262bf44d3]
然后我们只要在程序里边这么写就可以了:
[code:1:3262bf44d3]
$pager_option = array(
"sql" => $sql,
"pagesize" => 10,
"currentpageid" => $page
);
if ( isset($_get['numitems']) )
{
$pager_option['numitems'] = (int)$_get['numitems'];
}
$pager = new pager($pager_option);
[/code:1:3262bf44d3]
这段代码在我文章里的示例里也有体现,这样处理以后,除了第一次需要去记算总条数以外,以后的翻页都直接使用上一次查询出来的数据,这样效率得到了提高。
--------------------------------------------------------------------------------
tonera 回复于:2003-10-27 10:32:05
要是我想实现每页显示指定数量的页码,怎么办?
例如:
有1000个记录,每页显示10条。
当我看到第5页时,显示的是51-60条记录。
同时我想让它显示页码:1 2 3 4 6 7 8 9
当我翻到第10页时,显示:
6 7 8 9 11 12 13 14
--------------------------------------------------------------------------------
nightkids 回复于:2003-10-27 10:47:10
我也凑热闹~~~我的分页类~~~
[code:1:cb1d006774]
<?php
ob_start();
/*
* copyright (c) 2003 nightkids <[email protected]>
* all rights reserved.
*
* redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* this software is provided by the author and contributors ``as is'' and
* any express or implied warranties, including, but not limited to, the
* implied warranties of merchantability and fitness for a particular purpose
* are disclaimed. in no event shall the author or contributors be liable
* for any direct, indirect, incidental, special, exemplary, or consequential
* damages (including, but not limited to, procurement of substitute goods
* or services; loss of use, data, or profits; or business interruption)
* however caused and on any theory of liability, whether in contract, strict
* liability, or tort (including negligence or otherwise) arising in any way
* out of the use of this software, even if advised of the possibility of
* such damage.
*/
//ob_start("ob_gzhandler");
//set_time_limit(10);
/*************************************************************************************************************
* the php file create by black wind
* e-mail:[email protected];[email protected]
* 主页:
* qq:9400355,30148292
* 作者:black wind
*
*
*
* 最后修改时间:
*
* 声明:任何个人或团体可以任意修改、传播代码、可以用于任何场所(造成的任何损失或纠纷与本人无关)。
* 如果有什么好的建议和意见请与我联系。
* 请你在使用或传播是请保留这段注释,尊重本人的劳动成果。谢谢!!
*
* 感谢:所有身边的朋友、所有支持我的人们。
* 所有无私提供资料的网友和朋友们。所有 php 支持者 !
*
*
* 开发环境:apache/1.3.27+php 4.3.0rc4+zend engine v1.3.0+mysql 4.0.4-beta-max-nt+zend optimizer v2.0.3
*
* 要求:
*************************************************************************************************************/
//_server["http_referer"]; //http://black-server/studio/
//_server["query_string"]; //返回问号后面的字符串
//_get["变量名"]; //可以取回传入的一个变量
//_server["request_uri"];//返回 /studio/php_info.php?pp=阿嗄&kl=00&uj=90l
//_server["argv"];以数组形式返回传入的值
//_server["script_name"];
//----------- the file the start --------
//require_once("");
//include_once("");
/*
本类没有提供连接数据库的功能,所以需在外部打开相应的数据库。
本类也没有提供显示记录的功能,只是分页读取记录至 result二维数组中。
需在外部自定义数据显示格式。
$tp = new tviewpage();
$tp->setsqlbuff($sqlbuff);
$tp->setpagequery("action","null");
$row=$tp->readlist();
$rowcount=count($row)-1;
$thepage=$tp->thepage();
$page=$tp->page1();
*/
class tviewpage
{
//var $dbc; //数据库链接
var $maxline=10; //每页显示行数
var $offset; //记录偏移量
var $total=0; //记录总数
var $number; //本页读取的记录数
var $result; //读出的结果
var $tpages=0; //总页数
var $cpages; //当前页数
var $condition; //显示条件 如:where id='$id' order by id desc
var $pagequery; //分页显示要传递的参数
var $column; //显示的列
var $parkey;
var $debug=false;
var $_sqlbuff=null;
var $php_self;
var $vpdispnum=8;//分页条数字显示个数 样式 3 使用
/*
nightkids
2003-10-20 15:04:59 添加 wap 版本分页
**/
var $iswap=false;
//******构造函数*************
//参数:表名、最大行数、偏移量
function tviewpage($ml=10)
{
global $offset;
$offset=$_get[offset];
$this->maxline=$ml;
$this->column=$column;
if(isset($offset)) $this->offset=intval($offset);
else $this->offset=0;
$this->php_self=$_server["script_name"];
}
function setsqlbuff($sqlbuff) //使用外部的 sql 指令
{ $this->_sqlbuff=$sqlbuff;}
//********设置显示条件*********
//如:where id='$id' order by id desc
//要求是字串,符合sql语法(本字串将加在sql语句后)
//******设置传递参数************
// key参数名 value参数值 页面参数
// 如:setpagequery("id",$id);如有多个参数要传递,可多次调用本函数。
function setpagequery($key,$value)
{
$tmp[key]=$key;
$tmp[value]=$value;
$this->pagequery[]=$tmp;
}
//********读取记录***************
// 主要工作函数,根据所给的条件从表中读取相应的记录
// 返回值是一个二维数组,result[记录号][字段名]
function readlist()
{
$col=$this->column;
if($this->total==0)
{
$sqlbuff=$this->_sqlbuff;
$[email protected]_query($sqlbuff) or die(mysql_error());
$this->[email protected]_num_rows($result);
@mysql_free_result($result);
}
if($this->debug)
echo "<font color=red><hr>".$sqlbuff."<hr></font><br>";
if($this->total>0)
{ //根据条件 condition
$sql=$this->_sqlbuff." limit ".$this->offset." , ".$this->maxline;
$[email protected]_query($sql) or die(mysql_error());
$this->[email protected]_num_rows($result);
while($[email protected]_fetch_array($result))
{ $this->result[]=$row; }
@mysql_free_result($result);
}
return $this->result;
}
//**********显示页数*************
//显示当前页及总页数
function thepage()
{
$tmpstr="总数 <b>".$this->totalnum()." </b>";
return $tmpstr." 第<b>".$this->currentpage()."</b>页/共<b>".$this->totalpages()."</b>页";
}
function totalnum() //总纪录数
{
return $this->total;
}
function totalpages() //总页数
{
return $this->tpages=ceil($this->total/$this->maxline);
}
function currentpage() //当前页
{
return $this->cpages=$this->offset/$this->maxline+1;
}
function pagequerystr() //生成一个要传递参数字串
{
$k=count($this->pagequery);
$strquery=""; //生成一个要传递参数字串
$linkchar="&";
if($this->iswap) $linkchar="&";
for($i=0;$i<$k;$i++){
$strquery.="$linkchar".$this->pagequery[$i][key]."=".$this->pagequery[$i][value];
}
return $strquery;
}
function firstpageoffset() //第一页的偏移
{ return 0;}
function nextpageoffset() //下一页的偏移
{ return $this->offset+$this->maxline;}
function prevpageoffset() //上一页的偏移
{ return $this->offset-$this->maxline;}
function lastpageoffset() //最后一页的偏移
{ return ($this->totalpages()-1)*$this->maxline;}
//**********显示翻页按钮*************
//此函数要在thepage()函数之后调用!!!
//显示首页、下页、上页、未页,并加上要传递的参数
function page($style=null) //翻页样式1
{
if(!empty($style))
$".$style."/"";
$first=$this->firstpageoffset();
$next=$this->nextpageoffset();
$prev=$this->prevpageoffset();
$last=$this->lastpageoffset();
$strquery=$this->pagequerystr();
$linktmpstr=null;
$php_self=$this->php_self;
if($this->iswap==false){ //不是 wap 版本
if($this->offset>=$this->maxline)
{ $linktmpstr.="<a href=".$php_self."?offset=".$first.$strquery.$style.">首页</a> | ";}
if($prev>=0)
{$linktmpstr.="<a href=".$php_self."?offset=".$prev.$strquery.$style.">上一页</a> | "; }
if($next<$this->total)
{$linktmpstr.="<a href=".$php_self."?offset=".$next.$strquery.$style.">下一页</a> | "; }
if($this->tpages!=0 && $this->cpages<$this->tpages)
{$linktmpstr.="<a href=".$php_self."?offset=".$last.$strquery.$style.">末页</a>"; }
return $linktmpstr="<span $style>".$linktmpstr."</span>";
}else{
/*
if($this->offset>=$this->maxline)
{ $linktmpstr.="<a href=/"".$php_self."?offset=".$first.$strquery.$style."/">首页</a><br/>";}
*/
if($prev>=0)
{$linktmpstr.="<a href=/"".$php_self."?offset=".$prev.$strquery.$style."/">上一页</a><br/>"; }
if($next<$this->total)
{$linktmpstr.="<a href=/"".$php_self."?offset=".$next.$strquery.$style."/">下一页</a><br/>"; }
/*
if( ($this->tpages!=0) && ($this->cpages<$this->tpages) && ($this->tpages>1) )
{$linktmpstr.="<a href=/"".$php_self."?offset=".$last.$strquery.$style."/">末页</a><br/>"; }
*/
return $linktmpstr=$linktmpstr;
}
}
function page1($style=null) //翻页样式2
{
if(!empty($style))
$".$style."/"";
$first=$this->firstpageoffset();
$next=$this->nextpageoffset();
$prev=$this->prevpageoffset();
$last=$this->lastpageoffset();
$strquery=$this->pagequerystr();
$php_self=$this->php_self;
$firstpagestr="<span $style> <a href=/"".$php_self."?offset=".$first.$strquery.">首页</a> | </span>";
$nextpagestr="<span $style><a href=/"".$php_self."?offset=".$next.$strquery.">下一页</a> | </span>";
$prevpagestr="<span $style><a href=/"".$php_self."?offset=".$prev.$strquery.">上一页</a> | </span>";
$lastpagestr="<span $style> <a href=/"".$php_self."?offset=".$last.$strquery.">末页</a></span>";
$linktmpstr=null;
$offset=$this->offset;
$linktmpstr=null;
$currentpage=$this->currentpage();
$lastpage=$this->totalpages();
if($this->totalpages() <=1 ) return;
if($currentpage == 1)
{ return "<span".$style."> 首页 | 上一页 | </span>".$nextpagestr.$lastpagestr; }
if($currentpage==$lastpage)
{ return $firstpagestr.$prevpagestr."<span".$style.">下一页 | 末页</span>"; }
return $firstpagestr.$prevpagestr.$nextpagestr.$lastpagestr;
}
function page2($style=null) //样式3
{
if(!empty($style))
$".$style."/"";
$totalpage=$this->totalpages();
$currentpage=$this->currentpage();
$tmpstr="<select id='x99tvp' onchange='x99tvpc(this.value)'>/n";
$tmpstr="<select onchange=/"javascript:location.href='".$this->php_self."?offset='+this.value+'".$this->pagequerystr()."';this.disabled=true/" $style>/n";
for($i=1;$i<=$totalpage;$i++)
{
$nextoffset=($i-1)*$this->maxline;
$selected="";
if($i==$currentpage)
$selected="selected";
$tmpstr.="<option ".$selected." value=".$nextoffset.">".$i."</option>/n";
}
$tmpstr.="</select>/n";
return $tmpstr;
}
function page3($style=null) //样式4
{
if(!empty($style))
$".$style."/"";
$currentpage=$this->currentpage();
$boxsize=strlen($currentpage);
if($boxsize==1) $boxsize=1;
else $boxsize-=1;
$tmpstr="<input size='".$boxsize."' onkeydown='if(this.value.length>this.size)this.size=this.value.length-1' value='$currentpage' id='x99tvpbox' $style onfocus=/"this.select();/">";
$tmpstr.="<input type=/"button/" value=/"go/" onclick=/"javascript:location.href='".$this->php_self."?offset='+((x99tvpbox.value-1)*".$this->maxline.")+'".$this->pagequerystr()."';this.disabled=true;x99tvpbox.disabled=true/" $style>/n";
return $tmpstr;
}
//********************************end class
}
//----------- the file the end ----------
//如有意见或问题请致信到 [email protected];[email protected]
/*
$tp = new tviewpage();
$tp->setsqlbuff($sqlbuff);
$tp->setpagequery("action","null");
$row=$tp->readlist();
$rowcount=count($row)-1;
$thepage=$tp->thepage();
$page=$tp->page1();
使用实例:
function 李子(){
$tp = new tviewpage();
$sqlbuff="select * from `test` where `id`>100 ";
$tp->setsqlbuff($sqlbuff);
$tp->setpagequery("action","null");
$row=$tp->readlist();
$rownum=count($row);
#################
$tx = new z99template();
$tx->setvar("selfpage",$_server["script_name"]);
$tx->setfile("./template/");
$tx->setblock("blockromname");
###################
for($i=0;$i<=$rownum-1;$i++)
{
$tx->setvar("",$row[$i][id]);
$tx->addtoblock("blockromname");
}
$thepage=$tp->thepage();
$page=$tp->page1();
return $tx->onlyreturn();
}
*/
ob_end_flush();
?>
新闻热点
疑难解答