php之MySQL完美分页

来源:互联网 发布:14年流行的网络歌曲 编辑:程序博客网 时间:2024/04/29 00:52

自己学的MySQL完美分页,觉得以后用的着就写篇博客

输出效果图:(没有进行美化)



先在根目录下建立demo.php 和 page.class.php两个文件(demo.php为测试文件,page.class.php为分页类文件)

在数据库中建立自己相应的表,这里以sqldb库shops表为例




<?php  header("Content-Type:text/html;charset=utf-8");    include "page.class.php";    $link=mysql_connect("localhost", "root", "XXXXX");        mysql_select_db("sqldb");    $result=mysql_query("select * from shops");    $total=mysql_num_rows($result);    $num=5;    $page=new Page($total, $num);    $sql="select * from shops {$page->limit}";    $result=mysql_query($sql);

写出数据库数据输出内容的相应的表格

<?php    echo '<table align="center" width="1000" border="1">';    echo '<caption><h1>'.shop.'</h1></caption>';    while($row=mysql_fetch_assoc($result)){        echo '<tr>';        echo '<td>'.$row["id"].'</td>';        echo '<td>'.$row["name"].'</td>';        echo '<td>'.$row["price"].'</td>';        echo '<td>'.$row["num"].'</td>';        echo '<td>'.$row["desn"].'</td>';        echo '</tr>';    }
demo.php的内容基本就是以上两个(主要功能是连接数据库和设置输出的表格)

</pre>接下来就是分页类的书写<p>重点就是<span style="font-size:14px; color:#cc0000"><strong>page.class.php</strong></span>这个有关分页的类,主要也就写写本人认为重要的几点</p><p>定义的几个私有变量(这个不是什么重要的,只是提示一下下面代码变量的含义)</p><p></p><pre name="code" class="php"><?php    class Page{        private $total;   //数据表中总记录数        private $listRows;//每页显示行数        private $limit;        private $uri;        private $pageNum;   //页数        private $config=array('header'=>"记录","prev"=>"上一页","next"=>"下一页",                               "first"=>"首 页","last"=>"尾 页");
自动获取和解析访问当前的URL(这是整个page.class.php的重点)

private function getUri(){            $url=$_SERVER["REQUSET_URI"].(strpos($_SERVER["REQUEST_URI"], '?')?'':"?");            $parse=parse_url($url);                    if(isset($parse["query"])){                parse_str($parse['query'],$params);  //解析字符串                unset($params["page"]);   //删除page                $url=$parse['path'].'?'.http_build_query($params);   //路径加组合page            }            if(strstr($url, '?')){                if(substr($url, -1)!='?')                    $url = $url."&";            }else{                $url = $url.'?';            }            return $url;        }

下面就对几个按钮进行操作

先要获取开始位置

//开始取得位置        private function setLimit(){            return "Limit ".($this->page-1)*$this->listRows.", {$this->listRows}";        }

然后对几个按钮进行操作(首页,上一页,下一页,尾页,数字按钮,跳转按钮)

其中"首页","上一页","下一页","尾页" 的方法基本相似,以“首页”为例

private function first(){            if($this->page==1)                $html.='';            else                $html.=" <a href='{$this->uri}&page=1'>{$this->config["first"]}</a> ";            return $html;        }
数字按钮:pageList()

要考虑到点击数字时数字不会消失,显示的数字按钮不会超过实际的页数也不会是负数

 private function pageList(){            $linkPage="";            //保证分页数显示的数目(输出一半)            $inum=floor($this->listNum/2);            for($i=$inum;$i>=1;$i--){                $page=$this->page-$i;  //当前页减1                if($page<1)                    continue;   //页数小于1.退出                $linkPage.="<a href='{$this->uri}&page={$page}'>{$page}</a> ";            }               $linkPage.="{$this->page} ";   //显示当前页                        for($i=1;$i<=$inum;$i++){                $page=$this->page+$i;   //当前页加i                if($page<=$this->pageNum)  //当前页小于等于页数时输出                    $linkPage.="<a href='{$this->uri}&page={$page}'>{$page}</a> ";                else                    break;            }            return $linkPage;        }

GO按钮跳转

也是重点的部分,主要是采用了  javascript  的知识,用  javascript  实现起来相对简单一些

注意的是:回车监听和按钮监听其实是差不多的,不过按钮监听要用的是this.previousSibling.value,为了清除上一个的值

private function goPage(){            if($this->pageNum > 1){            return '<input type="text" onkeydown="javascript:if(event.keyCode==13){var page=(this.value >'.$this->pageNum.')                    ?'.$this->pageNum.':this.value;location=\''.$this->uri.'&page=\'+page+\'\'}"                      value="'.$this->page.'" style="width:25px">                      <input type="button" value="GO" onclick="javascript:var page=(this.previousSibling.value >'.$this->pageNum.')                    ?'.$this->pageNum.':this.previousSibling.value;location=\''.$this->uri.'&page=\'+page+\'\'">';                    //previousSibling为上一个同包的值        }

最后就是将输出分页指定格式

function fpage($display=array(0,1,2,3,4,5,6,7,8)){            $html[0]="共有<b>{$this->total}</b>{$this->config["header"]} ";            $html[1]="每页显示<b>".($this->end()-$this->start()+1)."</b>条,本页<b>{$this->start()}-                    {$this->end()}</b>条 ";            $html[2]="<b>{$this->page}/{$this->pageNum}</b> ";            $html[3]=$this->first();            $html[4]=$this->prev();            $html[5]=$this->pageList();            $html[6]=$this->next();            $html[7]=$this->last();            $html[8]=$this->goPage();            $fpage="";            foreach ($display as $index) {                $fpage.=$html[$index];            }            return $fpage;                }


最后放上完整的代码:

demo.php

<?php    header("Content-Type:text/html;charset=utf-8");    include "page.class.php";    $link=mysql_connect("localhost", "root", "XXXXX");        mysql_select_db("sqldb");    $result=mysql_query("select * from shops");    $total=mysql_num_rows($result);    $num=5;    $page=new Page($total, $num);    $sql="select * from shops {$page->limit}";    $result=mysql_query($sql);    echo '<table align="center" width="1000" border="1">';    echo '<caption><h1>'.shop.'</h1></caption>';    while($row=mysql_fetch_assoc($result)){        echo '<tr>';        echo '<td>'.$row["id"].'</td>';        echo '<td>'.$row["name"].'</td>';        echo '<td>'.$row["price"].'</td>';        echo '<td>'.$row["num"].'</td>';        echo '<td>'.$row["desn"].'</td>';        echo '</tr>';    }    echo '<tr><td colspan="5" align="right">'.$page->fpage(array(8,3,4,5,6,7,0,1,2)).'</td></tr>';    echo '</table>';

page.class.php

<?php    class Page{        private $total;   //数据表中总记录数        private $listRows;//每页显示行数        private $limit;        private $uri;        private $pageNum;   //页数        private $config=array('header'=>"记录","prev"=>"上一页","next"=>"下一页",                               "first"=>"首 页","last"=>"尾 页");        private $listNum=8;   //提供一个用户可改的长度变量        /*         *$total         *$listRows         */        public function __construct($total, $listRows=10){            $this->total=$total;            $this->listRows=$listRows;            $this->uri=$this->getUri();            //当前页            $this->page=!empty($_GET["page"]) ? $_GET["page"] : 1;            $this->pageNum=ceil($this->total/$this->listRows);            $this->limit=$this->setLimit();            var_dump($this);        }        //开始取得位置        private function setLimit(){            return "Limit ".($this->page-1)*$this->listRows.", {$this->listRows}";        }        private function getUri(){            $url=$_SERVER["REQUSET_URI"].(strpos($_SERVER["REQUEST_URI"], '?')?'':"?");            $parse=parse_url($url);                    if(isset($parse["query"])){                parse_str($parse['query'],$params);  //解析字符串                unset($params["page"]);   //删除page                $url=$parse['path'].'?'.http_build_query($params);   //路径加组合page            }            if(strstr($url, '?')){                if(substr($url, -1)!='?')                    $url = $url."&";            }else{                $url = $url.'?';            }            return $url;        }        private function __get($args){            if($args=="limit" || $args=="page"){                return $this->limit;            }else{                return null;            }        }        //开始位置        private function start(){            if($this->total==0)                return 0;            else                return ($this->page-1)*$this->listRows+1;        }        //结束位置        private function end(){            return min($this->page*$this->listRows,$this->total);        }        private function first(){            if($this->page==1)                $html.='';            else                $html.=" <a href='{$this->uri}&page=1'>{$this->config["first"]}</a> ";            return $html;        }        private function prev(){            if($this->page==1)                $html.='';            else                $html.=" <a href='{$this->uri}&page=".($this->page-1)."'>{$this->config["prev"]}</a> ";            return $html;        }        private function pageList(){            $linkPage="";            //保证分页数显示的数目(输出一半)            $inum=floor($this->listNum/2);            for($i=$inum;$i>=1;$i--){                $page=$this->page-$i;  //当前页减1                if($page<1)                    continue;   //页数小于1.退出                $linkPage.="<a href='{$this->uri}&page={$page}'>{$page}</a> ";            }               $linkPage.="{$this->page} ";   //显示当前页                        for($i=1;$i<=$inum;$i++){                $page=$this->page+$i;   //当前页加i                if($page<=$this->pageNum)  //当前页小于等于页数时输出                    $linkPage.="<a href='{$this->uri}&page={$page}'>{$page}</a> ";                else                    break;            }            return $linkPage;        }        private function next(){            if($this->page==$this->pageNum)                $html.='';            else                $html.=" <a href='{$this->uri}&page=".($this->page+1)."'>{$this->config["next"]}</a> ";            return $html;        }        private function last(){            if($this->page==$this->pageNum)                $html.='';            else                $html.=" <a href='{$this->uri}&page=".($this->pageNum)."'>{$this->config["last"]}</a> ";            return $html;        }        private function goPage(){            if($this->pageNum > 1){            return '<input type="text" onkeydown="javascript:if(event.keyCode==13){var page=(this.value >'.$this->pageNum.')                    ?'.$this->pageNum.':this.value;location=\''.$this->uri.'&page=\'+page+\'\'}"                      value="'.$this->page.'" style="width:25px">                      <input type="button" value="GO" onclick="javascript:var page=(this.previousSibling.value >'.$this->pageNum.')                    ?'.$this->pageNum.':this.previousSibling.value;location=\''.$this->uri.'&page=\'+page+\'\'">';                    //previousSibling为上一个同包的值        }    }        function fpage($display=array(0,1,2,3,4,5,6,7,8)){            $html[0]="共有<b>{$this->total}</b>{$this->config["header"]} ";            $html[1]="每页显示<b>".($this->end()-$this->start()+1)."</b>条,本页<b>{$this->start()}-                    {$this->end()}</b>条 ";            $html[2]="<b>{$this->page}/{$this->pageNum}</b> ";            $html[3]=$this->first();            $html[4]=$this->prev();            $html[5]=$this->pageList();            $html[6]=$this->next();            $html[7]=$this->last();            $html[8]=$this->goPage();            $fpage="";            foreach ($display as $index) {                $fpage.=$html[$index];            }            return $fpage;                }    }








0 0
原创粉丝点击