MySQL完美分頁

來源:互聯網
上載者:User

標籤:php

自己學的MySQL完美分頁,覺得以後用的著就寫篇部落格

輸出:(沒有進行美化)



先在根目錄下建立demo.php 和 page.class.php兩個檔案(demo.php為測試檔案,page.class.php為分頁類檔案)

在資料庫中建立自己相應的表,這裡以sqldb庫shops表為例

</pre><p><span style="font-size:12px"><img src="http://img.blog.csdn.net/20150313220931373?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvaHlmOTM5MjQ=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" /></span></p><p><span style="font-size:12px"><img src="http://img.blog.csdn.net/20150313221114815?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvaHlmOTM5MjQ=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" /></span></p><p></p><p>PHP串連資料庫(demo.php串連資料庫),選擇庫名</p><p></p><pre name="code" class="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);

寫出資料庫資料輸出內容的相應的表格

<?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;                }    }








MySQL完美分頁

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.