>  기사  >  백엔드 개발  >  PHP如何实现网页分页效果

PHP如何实现网页分页效果

WBOY
WBOY원래의
2016-06-20 12:47:281435검색

   在PHP网站之说,有很多需要实现分页效果,主要是用于阅读小说。

 功能实现如下:

使用sql查询进行分页时,需要调用几个函数,具体见脚本:
1.pager.class.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 sql with no connection', true);
                        return false;
                        }
                $this->_query_id = @mysql_query($query, $this->_conn);
                if ($this->_query_id === false) {
                $this->_errstr = @mysql_error();
                $ret = false;
                 } else {
                $this->_errstr = 'SUCCESS';
                $ret = $this->_query_id;
                        }
                }
                 $msg = ($ret === false) ? 'false' : strval($ret);
                 debugLog(__METHOD__.": [$msg] returned for sql 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->datanum == 0){
                                return 1;
                        }else{
                                return ceil($this->datanum/$this->page_size);
                        }
                }
//数据库查询的偏移量
                public function start() {
                        return ($this->page_id()-1)*$this->page_size;
                }

                //数据输出
                public function sqlquery() {
                        return $this->sql." limit ".$this->start().",".$this->page_size;
                }

                //获取当前文件名
                private function php_self() {
                        return $_SERVER['PHP_SELF'];
                }

                //上一页
                private function pre_page() {
                        if ($this->page_id() == 1) { //页数等于1
                                return "url().">上一页 ";
                        }elseif ($this->page_id() != 1) { //页数不等于1
                                return "page_id()-1).$this->url().">上一页 ";
                        }
                }

                //显示分页
                private function display_page() {
                        $display_page = "";
                        if($this->page_num()                                 for ($i=1;$ipage_num();$i++)  //循环显示出页面
                                        $display_page .= "url().">".$i." ";
                                        return $display_page;
                        }elseif($this->page_num() > 10){ //大于10页
                                if($this->page_id()                                         for ($i=1;$i                                                 $display_page .= "url().">".$i." ";
                                                return $display_page;
                                }elseif(($this->page_id() > 6) && ($this->page_num()-$this->page_id() >= 4)){
                                        for ($i=$this->page_id()-5;$ipage_id()+4;$i++) //循环显示出页面
                                                $display_page .= "url().">".$i." ";
 return $display_page;
                                }elseif(($this->page_id() > 6) && ($this->page_num()-$this->page_id()                                         for ($i=$this->page_num()-9;$ipage_num();$i++) //循环显示出页面
                                                $display_page .= "url().">".$i." ";
                                                return $display_page;
                                }
                        }
                }

                //下一页
                private function next_page() {
                        if ($this->page_id() page_num()) { //页数小于总页数
                                return "page_id()+1).$this->url().">下一页 ";
                        }elseif ($this->page_id() == $this->page_num()) { //页数等于总页数
                                return "page_num().$this->url().">下一页 ";
                        }
                }

                // 设置分页信息
                public function set_page_info() {
                        $page_info = "共".$this->datanum."条 ";
                        $page_info .= "url().">首页 ";
                        $page_info .= $this->pre_page();
                        $page_info .= $this->display_page();
                        $page_info .= $this->next_page();
                        $page_info .= "page_num().$this->url().">尾页 ";
                        $page_info .= "第".$this->page_id()."/".$this->page_num()."页";
                        return $page_info;
                }

        }
?>
2.脚本2:
        //类的用法
        // 读取分页类
        include("pager.class.php");
        // 数据库连接初始化
//      $db = new mysql();
        $impeach_host = '10.81.43.139';
        $impeach_usr = 'vmtest15';
        $impeach_passwd = 'vmtest15';
        $impeach_name = 'ufeature';
        $impeach_con = mysql_connect($impeach_host, $impeach_usr, $impeach_passwd) or
             die("Can't connect ".mysql_error());
        mysql_select_db($impeach_name, $impeach_con);
        // 这是一个sql查询语句,并得到查询结果
        $sql = "select word from ufeature.spam_accuse_word_list where flag='0'";
        // 分页初始化
        $page = new pager($sql,20);
        // 20是每页显示的数量
        //  $res_1 = mysql_query($sql) or
        //             die("Can't get result ".mysql_error());

         $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用法

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 每页条数 , 每页条数
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解析成有固定键值的数组的函数

 

例子
$ua=parse_url("http://username:password@hostname/path?arg=value#anchor");
print_r($ua);
结果:

Array
(
    [scheme] => http                ;协议
    [host] => hostname              ;主机域名

    [user] => username              ;用户
    [pass] => password              ;密码
    [path] => /path                 ;路径
    [query] => arg=value            ;取参数

    [fragment] => anchor            ;
)

 


5、代码实例

 这个一个留言的分页,分为3个部分,一个是数据库设计,一个是连接页面,一个是显示页面。

(1)设计数据库

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

(2)连接页面

$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)显示页面

 include("conn.php");

$pagesize=2;        //设置每页显示2个记录
$url=$_SERVER["REQUEST_URI"];  
$url=parse_url($url);
$url=$url[path];


$numq=mysql_query("SELECT * FROM `message`");
$num = mysql_num_rows($numq);

if($_GET[page]){
$pageval=$_GET[page];
$page=($pageval-1)*$pagesize;
$page.=',';
}
if($num > $pagesize){
 if($pageval

 echo "共 $num 条".
 " 上一页 下一页";
}
$SQL="SELECT * FROM `message` limit $page $pagesize ";
    $query=mysql_query($SQL);
 
  while($row=mysql_fetch_array($query)){
?>


  
  
  
  
  
  
  
  
  
  

标题: 时间:
用户:
内容:

  }
?>
(4)最后显示


方法3:

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

脚本2:


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 { 
//$result=mysql_query("select count(title) from " . TBL_Comments ." where `title`=\"".$title[$a]."\""); 
//$row = mysql_fetch_row($result); 
echo "

\n"; 
echo "\n"; 
echo "\n"; 
echo "\n"; 
echo "\n"; 
echo " \n"; 
echo "\n"; 
echo "
\n"; 
//rating_bar($title[$a],5); 
echo "
$hotelname[$a]\n"; 
echo "
\n"; 
echo "PHP如何实现网页分页效果  推荐人数:($countpeople[$a]) |\n"; 
echo "平均分: (".$count."票) | 评论数:()\n"; 
echo "
\n"; 

echo "
echo "border=0>"; 
echo ""; 
echo "
"; 
echo "

第".$page."页/总".$pages."页 | 总".$numrows."条 | "; 
if ($page>1) echo "首页 | "; 
if ($page>1) echo "上页 | "; 
if ($page下页 | "; 
if ($page尾页"; 
echo "转到第 "; 
echo "

";

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.