php实现分页功能的3种方法

前端之家收集整理的这篇文章主要介绍了php实现分页功能的3种方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

直接上代码,希望大家仔细阅读。

方法一:讲SQL查询进行分页进行,需要调用几个函数,具体见脚本:

1.pager.class.PHP

PHP;"> class pager {
public $sql; //SQL查询语句
public $datanum; //查询所有的数据总记录数
public $page_size; //每页显示记录的条数
protected $_errstr;
protected $_conn;
protected $_query_id;

public function query($query)///这个函数有问题,暂时可以不用
{
$ret = false;
if (!empty($query)) {
  if ($this->_conn === false || !is_resource($this->_conn)) {
   warningLog(__METHOD__ . ': query <a href="https://www.jb51.cc/tag/sql/" target="_blank" class="keywords">sql</a> with no connection',true);
  return false;
  }
$this->_query_id = @<a href="https://www.jb51.cc/tag/MysqL/" target="_blank" class="keywords">MysqL</a>_query($query,$this->_conn);
if ($this->_query_id === false) {
$this->_errstr = @<a href="https://www.jb51.cc/tag/MysqL/" target="_blank" class="keywords">MysqL</a>_error();
$ret = false;
 } else {
$this->_errstr = 'SUCCESS';
$ret = $this->_query_id;
  }
}
 $msg = ($ret === false) ? 'false' : strval($ret);
 debugLog(__METHOD__.": [$msg] returned for <a href="https://www.jb51.cc/tag/sql/" target="_blank" class="keywords">sql</a> query [$query]");
return $ret;
}

function __construct($sql,$page_size) {
$result = MysqL_query($sql);
$datanum = MysqL_num_rows($result);
$this->sql=$sql;
$this->datanum=$datanum;
$this->page_size=$page_size;
}

//当前页数
public function page_id() {
  if($_SERVER['QUERY_STRING'] == ""){
    return 1;
  }elseif(substr_count($_SERVER['QUERY_STRING'],"page_id=") == 0){
    return 1;
  }else{
    return intval(substr($_SERVER['QUERY_STRING'],8));
  }
}

//剩余url值
public function url() {
  if($_SERVER['QUERY_STRING'] == ""){
    return "";
  }elseif(substr_count($_SERVER['QUERY_STRING'],"page_id=") == 0){
    return "&".$_SERVER['QUERY_STRING'];
  }else{
    return str_replace("page_id=".$this->page_id(),"",$_SERVER['QUERY_STRING']);
  }
}

//总页数
public function page_num() {
  if($this->d<a href="https://www.jb51.cc/tag/atan/" target="_blank" class="keywords">atan</a>um == 0){
    return 1;
  }else{
    return ceil($this->d<a href="https://www.jb51.cc/tag/atan/" target="_blank" class="keywords">atan</a>um/$this->page_size);
  }
}

//数据库查询的偏移量
public function start() {
return ($this->page_id()-1)*$this->page_size;
}

//数据<a href="https://www.jb51.cc/tag/shuchu/" target="_blank" class="keywords">输出</a>
public function <a href="https://www.jb51.cc/tag/sql/" target="_blank" class="keywords">sql</a>query() {
  return $this-><a href="https://www.jb51.cc/tag/sql/" target="_blank" class="keywords">sql</a>." limit ".$this->start().",".$this->page_size;
}

//<a href="https://www.jb51.cc/tag/huoqu/" target="_blank" class="keywords">获取</a>当前<a href="https://www.jb51.cc/tag/wenjian/" target="_blank" class="keywords">文件</a>名
private function <a href="https://www.jb51.cc/tag/PHP/" target="_blank" class="keywords">PHP</a>_self() {
  return $_SERVER['<a href="https://www.jb51.cc/tag/PHP/" target="_blank" class="keywords">PHP</a>_SELF'];
}

//<a href="https://www.jb51.cc/tag/shangyiye/" target="_blank" class="keywords">上一页</a>
private function pre_page() {
  if ($this->page_id() == 1) { //页数等于1
    return "<a href=".$this->php_self()."?page_id=1".$this->url()."&gt;上一页</a> ";
  }elseif ($this->page_id() != 1) { //页数不等于1
    return "<a href=".$this->php_self()."?page_id=".($this->page_id()-1).$this->url()."&gt;上一页</a> ";
  }
}

//<a href="https://www.jb51.cc/tag/xianshi/" target="_blank" class="keywords">显示</a><a href="https://www.jb51.cc/tag/fenye/" target="_blank" class="keywords">分页</a>
private function display_page() {
  $display_page = "";
  if($this->page_num() <= 10){ //小于10页
    for ($i=1;$i<=$this->page_num();$i++) //循环<a href="https://www.jb51.cc/tag/xianshi/" target="_blank" class="keywords">显示</a>出<a href="https://www.jb51.cc/tag/yemian/" target="_blank" class="keywords">页面</a>
      $display_page .= "<a href=".$this->php_self()."?page_id=".$i.$this->url()."&gt;".$i."</a> ";
      return $display_page;
  }elseif($this->page_num() > 10){ //大于10页
    if($this->page_id() <= 6){
      for ($i=1;$i<=10;$i++) //循环显示出页面
        $display_page .= "<a href=".$this->php_self()."?page_id=".$i.$this->url()."&gt;".$i."</a> ";
        return $display_page;
    }elseif(($this->page_id() > 6) && ($this->page_num()-$this->page_id() >= 4)){
      for ($i=$this->page_id()-5;$i<=$this->page_id()+4;$i++) //循环<a href="https://www.jb51.cc/tag/xianshi/" target="_blank" class="keywords">显示</a>出<a href="https://www.jb51.cc/tag/yemian/" target="_blank" class="keywords">页面</a>
        $display_page .= "<a href=".$this->php_self()."?page_id=".$i.$this->url()."&gt;".$i."</a> ";

return $display_page;
}elseif(($this->page_id() > 6) && ($this->page_num()-$this->pageid() @H502_12@page_num()-9;$i<=$this->page_num();$i++) //循环显示页面
$display_page .= "<a href=".$this->php_self()."?page_id=".$i.$this->url().">".$i." ";
return $display_page;
}
}
}

//<a href="https://www.jb51.cc/tag/xiayiye/" target="_blank" class="keywords">下一页</a>
private function next_page() {
  if ($this->page_id() < $this->page_num()) { //页数小于总页数
    return "<a href=".$this->php_self()."?page_id=".($this->page_id()+1).$this->url()."&gt;下一页</a> ";
  }elseif ($this->page_id() == $this->page_num()) { //页数等于总页数
    return "<a href=".$this->php_self()."?page_id=".$this->page_num().$this->url()."&gt;下一页</a> ";
  }
}

// 设置<a href="https://www.jb51.cc/tag/fenye/" target="_blank" class="keywords">分页</a>信息
public function set_page_info() {
  $page_info = "共".$this->d<a href="https://www.jb51.cc/tag/atan/" target="_blank" class="keywords">atan</a>um."条 ";
  $page_info .= "<a href=".$this->php_self()."?page_id=1".$this->url()."&gt;首页</a> ";
  $page_info .= $this->pre_page();
  $page_info .= $this->display_page();
  $page_info .= $this->next_page();
  $page_info .= "<a href=".$this->php_self()."?page_id=".$this->page_num().$this->url()."&gt;尾页</a> ";
  $page_info .= "第".$this->page_id()."/".$this->page_num()."页";
  return $page_info;
}

}
?>

2.脚本2:

$result=mysql_query($page->sqlquery());
while($info = MysqL_fetch_array($result,MysqL_ASSOC)){

// while($info = MysqL_fetch_array($res_1,MysqL_ASSOC)){
echo $info["word"]."
";
}
// 页码索引条
echo $page->set_page_info();

?>

方法二:使用ajax的方法

1、首先了解sql语句中的limit用法

sql;"> SELECT * FROM table …… limit 开始位置 , 操作条数 (其中开始位置是从0开始的)

取前20条记录:SELECT * FROM table …… limit 0 , 20 从第11条开始取20条记录:SELECT * FROM table …… limit 10 , 20 LIMIT n 等价于 LIMIT 0,n。 如

select * from table LIMIT 5; //返回前5行,

select * from table LIMIT 0,5

一样 2、分页原理

所谓分页显示,也就是讲数据库中的结果集,一段一段显示出来 怎么分段,当前在第几段 (每页有几条,当前再第几页) 前10条记录:

select * from table limit 0,10

第11至20条记录:

select * from table limit 10,10

第21至30条记录:

select * from table limit 20,10

分页公式:

(当前页数 - 1 )X 每页条数 , 每页条数

sql;"> Select * from table limit ($Page- 1) * $PageSize,$PageSize

3、$_SERVER["REQUEST_URI"]函数 预定义服务器变量的一种,所有$_SERVER开头的都叫做预定于服务器变量。 REQUEST_URI的作用是取得当前URI,也就除域名外后面的完整的地址路径。 例子: 当前页为:http://www.test.com/home.PHP?id=23&cid=22 echo $_SERVER["REQUEST_URI"] 结果为:/home.PHP?id=23&cid=22 4、parse_url()解析URL函数 parse_url() 是讲URL解析成有固定键值的数组的函数 例子

结果:

http ;协议 [host] => hostname ;主机域名 [user] => username ;用户 [pass] => password ;密码 [path] => /path ;路径 [query] => arg=value ;取参数 [fragment] => anchor ; )

5、代码实例 这个一个留言的分页,分为3个部分,一个是数据库设计,一个是连接页面,一个是显示页面

(1)设计数据库

设计数据库名为bbs,有一个数据表为message,里面包含title,lastdate,user,content等字段,分别表示留言标题,留言日前,留言人,留言的内容

(2)连接页面

PHP;"> PHP $conn = @ MysqL_connect("localhost","root","123456") or die("数据库链接错误"); MysqL_select_db("bbs",$conn); MysqL_query("set names 'GBK'"); //使用GBK中文编码; //将空格,换行转换为HTML可解析 function htmtocode($content) { $content = str_replace("\n","
",str_replace(" ",$content)); //两个str_replace嵌套 return $content; } //$content=str_replace("'","‘",$content); //htmlspecialchars();

?>

(3)显示页面

PHP;"> $numq=mysql_query("SELECT FROM message");
$num = mysql_num_rows($numq);
if($_GET){
$pageval=$_GET;
$page=($pageval-1)
$pagesize;
$page.=',';
}
if($num > $pagesize){
if($pageval<=1)$pageval=1;
echo "共 $num 条".
" <a href=$url?page=".($pageval-1).">上一页 <a href=$url?page=".($pageval+1).">下一页";
}
$SQL="SELECT * FROM message limit $page $pagesize ";
$query=mysql_query($SQL);

while($row=mysql_fetch_array($query)){
?>
<table width=500 border="0" cellpadding="5" cellspacing="1" bgcolor="#add3ef">
<tr bgcolor="#eff3ff">
<td>标题:<?php echo $row[title]?></td> <td>时间:<?php echo $row[lastdate]?></td>
</tr>
<tr bgcolor="#eff3ff">
<td> 用户:<?php echo $row[user]?></td><td></td>
</tr>
<tr>
<td>内容:<?php echo htmtocode($row[content]);?></td>
</tr>


</table>
<?php
}
?>

方法3:

function viewpage(p){ if(window.XMLHttpRequest){ var xmlReq = new XMLHttpRequest(); } else if(window.ActiveXObject) { var xmlReq = new ActiveXObject('Microsoft.XMLHTTP'); } var formData = "page="+p; xmlReq.onreadystatechange = function(){ if(xmlReq.readyState == 4){ document.getElementByIdx_x('content2').innerHTML = xmlReq.responseText; } } xmlReq.open("post","hotel_list.PHP",true); xmlReq.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); xmlReq.send(formData); return false; }

PHP;"> header("Content-Type:text/html;charset=GB2312"); $pagesize=10; //echo $_POST['page']; $result = MysqL_query("Select count(DISTINCT hotelname) FROM ".TBL_HOTELS); $myrow = MysqL_fetch_array($result); $numrows=$myrow[0];

$pages=intval($numrows/$pagesize);
if ($numrows%$pagesize)
$pages++;
if (isset($_POST['page'])){
$page=intval($_POST['page']);
}
else{
//设置为第一页
$page=1;
}
$first=1;
$prev=$page-1;
$next=$page+1;
$last=$pages;
//计算记录偏移量
$offset=$pagesize($page - 1);
//读取指定记录数
$result=MysqL_query("select hotelname,count(
) from ".TBL_HOTELS." GROUP BY hotelname order by id desc limit $offset,$pagesize");
$num = MysqL_num_rows($result);
while ($row = MysqL_fetch_array($result,MysqL_NUM)) {
$hotelname[] = $row[0];
$countpeople[] = $row[1];
}
for($a=0;$a<$num;$a++)
{
//$result=MysqL_query("select count(title) from " . TBL_Comments ." where title=\"".$title[$a]."\"");
//$row = MysqL_fetch_row($result);
echo "<TABLE style=\"MARGIN-BOTTOM: 20px\" cellSpacing=0 cellPadding=0 width=100% border=0>\n";
echo "\n";
echo "\n";
echo "<TD style=\"PADDING-TOP: 5px\" vAlign=top align=left width=80>\n";
//rating_bar($title[$a],5);
echo "\n";
echo "<TD style=\"PADDING-TOP: 5px\" align=left width=100%><A title=$hotelname[$a] style=\"FONT-SIZE: 14px\" href=#>$hotelname[$a]\n";
echo "\n";
echo " \n";
echo "\n";
echo "<TD style=\"PADDING-LEFT: 0px\">\n";
echo "<IMG src=\"images/comment.gif\" border=0> 推荐人数:($countpeople[$a]) |\n";
echo "平均分:

(".$count."票) | 评论数:()\n";
echo "\n";
}
echo "<TABLE style=\"MARGIN-TOP: 30px\" cellSpacing=0 cellPadding=0 width=\"100%\"";
echo "border=0>";
echo "";
echo "
";
echo "

第".$page."页/总".$pages."页 | 总".$numrows."条 | ";
if ($page>1) echo "<a onclick=\"viewpage(".$first.")\" href='#'>首页 | ";
if ($page>1) echo "<a onclick=\"viewpage(".$prev.")\" href='#'>上页 | ";
if ($page<$pages) echo "<a onclick=\"viewpage(".$next.")\" href='#'>下页 | ";
if ($page<$pages) echo "<a onclick=\"viewpage(".$last.")\" href='#'>尾页";
echo "转到第 页 <INPUT hideFocus onclick=\"viewpage(document.all.goto_page.value)\" type=button value=Go name=cmd_goto>";
echo "

";

以上介绍了3种PHP实现分页功能方法,希望对大家的学习有所帮助。

原文链接:https://www.f2er.com/php/20998.html

猜你在找的PHP相关文章