PHP分頁類

實例演示簡易通用的PHP分頁類

關於php分頁類,網上有無數多個例子。水平參差不齊,孰優孰劣也沒有一一考量。但可以肯定的是,一定有很多優秀的代碼。開源最大的好處就是能使功能不斷的完善,分享也是一樣的道理,衆人拾柴火焰高嘛!

筆者在這裏把代碼貼出來,拋磚引玉。

先來看一下最終的顯示效果

1 .簡易php分頁類.png

這裏寫圖片描述

2 .[PHP]代碼

<?php
/***********************************************
 * @類名:   page
 * @參數:   $myde_total - 總記錄數
 *          $myde_size - 一頁顯示的記錄數
 *          $myde_page - 當前頁
 *          $myde_url - 獲取當前的url
 * @功能:   分頁實現
 * @作者:   源碼佈道者
 */
class page {
    private $myde_total;          //總記錄數
    private $myde_size;           //一頁顯示的記錄數
    private $myde_page;           //當前頁
    private $myde_page_count;     //總頁數
    private $myde_i;              //起頭頁數
    private $myde_en;             //結尾頁數
    private $myde_url;            //獲取當前的url
    /*
     * $show_pages
     * 頁面顯示的格式,顯示鏈接的頁數爲2*$show_pages+1。
     * 如$show_pages=2那麼頁面上顯示就是[首頁] [上頁] 1 2 3 4 5 [下頁] [尾頁] 
     */
    private $show_pages;

    public function __construct($myde_total=1,$myde_size=1,$myde_page=1,$myde_url,$show_pages=2){
        $this->myde_total = $this->numeric($myde_total);
        $this->myde_size = $this->numeric($myde_size);
        $this->myde_page = $this->numeric($myde_page);
        $this->myde_page_count = ceil($this->myde_total/$this->myde_size);
        $this->myde_url = $myde_url;
        if($this->myde_total<0) $this->myde_total=0;
        if($this->myde_page<1)  $this->myde_page=1;
        if($this->myde_page_count<1) $this->myde_page_count=1;
        if($this->myde_page>$this->myde_page_count) $this->myde_page=$this->myde_page_count;
        $this->limit = ($this->myde_page-1)*$this->myde_size;
        $this->myde_i=$this->myde_page-$show_pages;
        $this->myde_en=$this->myde_page+$show_pages;
        if($this->myde_i<1){
          $this->myde_en=$this->myde_en+(1-$this->myde_i);
          $this->myde_i=1;
        }
        if($this->myde_en>$this->myde_page_count){
          $this->myde_i = $this->myde_i-($this->myde_en-$this->myde_page_count);
          $this->myde_en=$this->myde_page_count;
        }
        if($this->myde_i<1)$this->myde_i=1;
    }
    //檢測是否爲數字
    private function numeric($num){
      if(strlen($num)){
         if(!preg_match("/^[0-9]+$/",$num)){
             $num=1;
           }else{
             $num = substr($num,0,11);
         }
      }else{
               $num=1;
      }
      return $num;
    }
    //地址替換
    private function page_replace($page){
        return str_replace("{page}",$page,$this->myde_url);
    }
    //首頁
    private function myde_home(){
        if($this->myde_page!=1){
            return "<a href="".$this->page_replace(1)."" title="首頁">首頁</a>";
        }else{
            return "<p>首頁</p>";
        }
    }
    //上一頁
    private function myde_prev(){
       if($this->myde_page!=1){
           return "<a href="".$this->page_replace($this->myde_page-1)."" title="上一頁">上一頁</a>";
       }else{
              return "<p>上一頁</p>";
       }
    }
    //下一頁
    private function myde_next(){
        if($this->myde_page!=$this->myde_page_count){
            return "<a href="".$this->page_replace($this->myde_page+1)."" title="下一頁">下一頁</a>";
        }else{
            return"<p>下一頁</p>";
        }
    }
    //尾頁
    private function myde_last(){
        if($this->myde_page!=$this->myde_page_count){
            return "<a href="".$this->page_replace($this->myde_page_count)."" title="尾頁">尾頁</a>";
        }else{
            return "<p>尾頁</p>";
        }
    }
    //輸出
    public function myde_write($id='page'){
       $str ="<div id="".$id."">";
       $str.=$this->myde_home();
       $str.=$this->myde_prev();
       if($this->myde_i>1){
            $str.="<p class="pageEllipsis">...</p>";
       }
       for($i=$this->myde_i;$i<=$this->myde_en;$i++){
            if($i==$this->myde_page){
                $str.="<a href="".$this->page_replace($i)."" title="".$i."" class="cur">$i</a>";
            }else{
          $str.="<a href="".$this->page_replace($i)."" title="".$i."">$i</a>";
            }
       }
       if( $this->myde_en<$this->myde_page_count ){
            $str.="<p class="pageEllipsis">...</p>";
       }
       $str.=$this->myde_next();
       $str.=$this->myde_last();
       $str.="<p class="pageRemark">共<b>".$this->myde_page_count.
             "</b>頁<b>".$this->myde_total."</b>條數據</p>";
       $str.="</div>";
       return $str;
    }
}
?>

3 .頁面代碼

<?php
require_once('./page.class.php'); //分頁類
$showrow = 3;//一頁顯示的行數
$curpage = empty($_GET['page'])?1:$_GET['page'];//當前的頁,還應該處理非數字的情況
$url = "?page={page}";//分頁地址,如果有檢索條件 ="?page={page}&q=".$_GET['q']
//省略了鏈接mysql的代碼,測試時自行添加
$sql = "SELECT * FROM table";
$query = mysql_query($sql);
$total = mysql_num_rows($query);//記錄總條數
if(!empty($_GET['page']) && $total !=0 && $curpage > ceil($total/$showrow))
$curpage = ceil($total_rows/$showrow);//當前頁數大於最後頁數,取最後一頁
//獲取數據
$get_data = "select * from table limit ".($curpage-1)*$showrow.",$showrow;";
...
?>

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>實例演示簡易通用的PHP分頁類</title>
<style type="text/css">
#page{
    height:40px;
    padding:20px 0px;
}
#page a{
    display:block;
    float:left;
    margin-right:10px;
    padding:2px 12px;
    height:24px;
    border:1px #cccccc solid;
    background:#fff;
    text-decoration:none;
    color:#808080;
    font-size:12px;
    line-height:24px;
}
#page a:hover{
    color:#077ee3;
    border:1px #077ee3 solid;
}
#page a.cur{
    border:none;
    background:#077ee3;
    color:#fff;
}
#page p{
    float:left;
    padding:2px 12px;
    font-size:12px;
    height:24px;
    line-height:24px;
    color:#bbb;
    border:1px #ccc solid;
    background:#fcfcfc;
    margin-right:8px;

}
#page p.pageRemark{
    border-style:none;
    background:none;
    margin-right:0px;
    padding:4px 0px;
    color:#666;
}
#page p.pageRemark b{
    color:red;
}
#page p.pageEllipsis{
    border-style:none;
    background:none;
    padding:4px 0px;
    color:#808080;
}
</style>
</head>

<body>
    <div class="main">
        <div class="showData">
            <!--顯示數據區-->
        </div>
        <div class="showPage">
          <?php
             if($total>$showrow){//總記錄數大於每頁顯示數,顯示分頁
             $page = new page($total,$showrow,$curpage,$url,2);
             echo $page->myde_write();
            }
          ?>
         </div>
    </div>
</body>
</html>

簡單分頁

/**
 * 自定義分頁方法
 * @param unknown_type $url     #分頁url,頁碼採用'%s'表示,例如:http://test.ebers.com/tags/xxx/%s/
 * @param unknown_type $cur_page        #當前頁碼
 * @param unknown_type $page_fix        #當前頁碼前後需要顯示多少個頁碼
 * @param intval $total_rows            #數據總數
 * @param intval $pagesize      #每頁顯示多少數據
 * @param string $cur_page_calss        #當前頁css樣式名稱
 */
public function pagenation($url, $cur_page=1, $page_fix=2, $total_rows=0, $pagesize=10, $cur_page_calss='disable'){
    #計算總頁數
    $pagesize = $pagesize>0?$pagesize:10;
    $total_page = ceil($total_rows / $pagesize);

    $code = '';
    if($total_page>1){
        $pager = array();
        #首頁
        $pager[] = sprintf( '<ul><li><a href="%s">首頁</a></li>', sprintf($url, 1) );

        #頁碼列表
        for($page_num=$cur_page-$page_fix; $page_num<$cur_page+$page_fix; $page_num++){
            if($page_num<1 || $page_num>$total_page){
                continue;
            }
            $pager[] = sprintf( '<li class="%s"><a href="%s">%s</a></li>', ( $page_num==$cur_page?$cur_page_calss:'' ), sprintf($url, $page_num), $page_num );
        }

        #末頁
        $pager[] = sprintf( '<li><a href="%s">末頁</a></li><li>共%s條,第%s/%s頁</li></ul>', sprintf($url, $total_page), $total_rows, $cur_page, $total_page );

        $code = implode("\n", $pager);
        unset($pager);
    }

    return $code;
}

PHP分頁類,支持自定義樣式,中間5頁等

<?php

//namespace Component;
/**
 * 2016-3-27
 * @author ankang
 */
class Page {
    private $ShowPage;
    private $CountPage;
    private $Floorp;
    private $PageUrl;
    private $PageClass;
    private $CurClass;

    /**
     * @author ankang
     * @param number $CountNum          數據總數
     * @param string $PageUrl           跳轉鏈接
     * @param string $PageClass         <a>標籤 總體樣式    
     * @param string $PageUrl           當前頁樣式
     * @param number $PageSize          每頁顯示的數據條數
     * @param number $ShowPage          每次顯示的頁數 
     */
    public function __construct($CountNum, $PageUrl = NULL, $PageClass = NULL,$CurClass = NULL, $PageSize = 20, $ShowPage = 5) {
        $this->ShowPage      = $ShowPage;
        $this->CountPage         = ceil ( $CountNum / $PageSize );
        $this->Floorp            = floor ( $ShowPage / 2 ); // 偏移量       
        $this->PageClass         = is_null ( $PageClass ) ? '' : $PageClass;
        $this->CurClass      = is_null ( $CurClass ) ? '' : $CurClass;

        // $ServerURL               = ( preg_match('/\?/i', $_SERVER['REQUEST_URI']))?preg_replace('/\&p\=[0-9]+/i', "", $_SERVER['REQUEST_URI']) : $_SERVER['REQUEST_URI']."?";
        // if( substr($ButURL,0,2)=='//' ){
            // $ServerURL          = substr($ServerURL,1);
        // }
        // $url                 = preg_replace('/p=[\d]*/i', '', $ServerURL);
           $url                 = '';
        //推薦自己傳url,不傳也可以打開上面的代碼自動獲取
        $this->PageUrl           = is_null ( $PageUrl ) ? $url : $PageUrl;
    }

    /**
     *
     * @param number $Page          
     * @param string $ShowToPage
     *          首頁,上下頁,尾頁
     * @param string $Html  標籤元素,li,p      
     * @return string
     */
    public function getPage($Page = 1, $ShowToPage = true, $Html = null) {
        $StartPage          = ($Page - $this->Floorp); // 開始頁碼
        $EndPage            = ($Page + $this->Floorp); // 結束頁碼

        if ($this->CountPage < $this->ShowPage) {
            $StartPage      = 1;
            $EndPage        = $this->CountPage;
        }

        if ($StartPage < 1) {
            $StartPage      = 1;
            $EndPage        = $this->ShowPage;
        }

        if ($EndPage > $this->CountPage) {
            $StartPage      = $this->CountPage - $this->ShowPage + 1;
            $EndPage        = $this->CountPage;
        }

        $PageHtml = '';

        if (! is_null ( $Html )) {
            if ($Html == 'li') {
                $Shtml = '<li>';
                $Ehtml = '</li>';
            } else {
                $Shtml = '<p>';
                $Ehtml = '</p>';
            }
        }

        if (true == $ShowToPage) {
            $PageHtml               .= "$Shtml<a href='{$this->PageUrl}p=1'>&laquo; 首頁</a>$Ehtml";
            $PrveUrl                 = $this->getPrve($Page);
            $PageHtml               .= "$Shtml<a href='{$PrveUrl}'>&laquo; 上一頁</a>$Ehtml";
        }

        for($i = $StartPage; $i <= $EndPage; $i ++) {
            if ($Page == $i) {
                $PageHtml           .= "$Shtml<a href='{$this->PageUrl}p={$i}' class='{$this->CurClass}'>{$i}</a>$Ehtml";
            } else {
                $PageHtml           .= "$Shtml<a href='{$this->PageUrl}p={$i}' class='{$this->PageClass}'>{$i}</a>$Ehtml";
            }
        }

        if (true == $ShowToPage) {
            $NextUrl                 = $this->getNext($Page);
            $PageHtml               .= "$Shtml<a href='{$NextUrl}'>下一頁 &raquo;</a>$Ehtml";
            $PageHtml               .= "$Shtml<a href='{$this->PageUrl}p={$this->CountPage}' >尾頁 &raquo;</a>$Ehtml";
        }

        return $PageHtml;
    }

    public function getPrve($Page){
        if ($Page != 1) {
            $Prve                = $Page - 1;
            $PrveUrl             = "{$this->PageUrl}p={$Prve}";
        } else {
            $PrveUrl             = "{$this->PageUrl}p=1";
        }

        return $PrveUrl;
    }

    public function getNext($Page){
        if ($Page != $this->CountPage) {
            $Next                = $Page + 1;
            $NextUrl             = "{$this->PageUrl}p={$Next}";
        } else {
            $NextUrl             = "{$this->PageUrl}p={$this->CountPage}";
        }

        return $NextUrl;
    }



}

萬能的分頁類

<?php
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * 分頁類
 * 使用方式:
 * $page = new Page();
 * $page->init(1000, 20);
 * $page->setNotActiveTemplate('<span>&nbsp;{a}&nbsp;</span>');
 * $page->setActiveTemplate('{a}');
 * echo $page->show();
 * 
 * 
 * @author 風居住的地方
 */
class Page {
    /**
     * 總條數
     */
    private $total;
    /**
     * 每頁大小
     */
    private $pageSize;
    /**
     * 總頁數
     */
    private $pageNum;
    /**
     * 當前頁
     */
    private $page;
    /**
     * 地址
     */
    private $uri;
    /**
     * 分頁變量
     */
    private $pageParam;
    /**
     * LIMIT XX,XX
     */
    private $limit;
    /**
     * 數字分頁顯示
     */
    private $listnum = 8;
    /**
     * 分頁顯示模板
     * 可用變量參數
     * {total}      總數據條數
     * {pagesize}   每頁顯示條數
     * {start}      本頁開始條數
     * {end}        本頁結束條數
     * {pagenum}    共有多少頁
     * {frist}      首頁
     * {pre}        上一頁
     * {next}       下一頁
     * {last}       尾頁
     * {list}       數字分頁
     * {goto}       跳轉按鈕
     */
    private $template = '<div><span>共有{total}條數據</span><span>每頁顯示{pagesize}條數據</span>,<span>本頁{start}-{end}條數據</span><span>共有{pagenum}頁</span><ul>{frist}{pre}{list}{next}{last}{goto}</ul></div>';
    /**
     * 當前選中的分頁鏈接模板
     */
    private $activeTemplate = '<li class="active"><a href="javascript:;">{text}</a></li>';
    /**
     * 未選中的分頁鏈接模板
     */
    private $notActiveTemplate = '<li><a href="{url}">{text}</a></li>';
    /**
     * 顯示文本設置
     */
    private $config = array('frist' => '首頁', 'pre' => '上一頁', 'next' => '下一頁', 'last' => '尾頁');
    /**
     * 初始化
     * @param type $total       總條數
     * @param type $pageSize    每頁大小
     * @param type $param       url附加參數
     * @param type $pageParam   分頁變量
     */
    public function init($total, $pageSize, $param = '', $pageParam = 'page') {
        $this->total = intval($total);
        $this->pageSize = intval($pageSize);
        $this->pageParam = $pageParam;
        $this->uri = $this->geturi($param);
        $this->pageNum = ceil($this->total / $this->pageSize);
        $this->page = $this->setPage();
        $this->limit = $this->setlimit();
    }

    /**
     * 設置分頁模板
     * @param type $template    模板配置
     */
    public function setTemplate($template) {
        $this->template = $template;
    }

    /**
     * 設置選中分頁模板
     * @param type $activeTemplate      模板配置
     */
    public function setActiveTemplate($activeTemplate) {
        $this->activeTemplate = $activeTemplate;
    }

    /**
     * 設置未選中分頁模板
     * @param type $notActiveTemplate   模板配置
     */
    public function setNotActiveTemplate($notActiveTemplate) {
        $this->notActiveTemplate = $notActiveTemplate;
    }

    /**
     * 返回分頁
     * @return type
     */
    public function show() {
        return str_ireplace(array(
            '{total}',
            '{pagesize}',
            '{start}',
            '{end}',
            '{pagenum}',
            '{frist}',
            '{pre}',
            '{next}',
            '{last}',
            '{list}',
            '{goto}',
        ), array(
            $this->total,
            $this->setPageSize(),
            $this->star(),
            $this->end(),
            $this->pageNum,
            $this->frist(),
            $this->prev(),
            $this->next(),
            $this->last(),
            $this->pagelist(),
            $this->gopage(),
        ), $this->template);
    }

    /**
     * 獲取limit起始數
     * @return type
     */
    public function getOffset() {
        return ($this->page - 1) * $this->pageSize;
    }

    /**
     * 設置LIMIT
     * @return type
     */
    private function setlimit() {
        return "limit " . ($this->page - 1) * $this->pageSize . ",{$this->pageSize}";
    }

    /**
     * 獲取limit
     * @param type $args
     * @return type
     */
    public function __get($args) {
        if ($args == "limit") {
            return $this->limit;
        } else {
            return null;
        }
    }

    /**
     * 初始化當前頁
     * @return int
     */
    private function setPage() {
        if (!empty($_GET[$this->pageParam])) {
            if ($_GET[$this->pageParam] > 0) {
                if ($_GET[$this->pageParam] > $this->pageNum)
                    return $this->pageNum;
                else
                    return $_GET[$this->pageParam];
            }
        }
        return 1;
    }

    /**
     * 初始化url
     * @param type $param
     * @return string
     */
    private function geturi($param) {
        $url = $_SERVER['REQUEST_URI'] . (strpos($_SERVER['REQUEST_URI'], "?") ? "" : "?") . $param;
        $parse = parse_url($url);
        if (isset($parse["query"])) {
            parse_str($parse["query"], $params);
            unset($params["page"]);
            $url = $parse["path"] . "?" . http_build_query($params);
            return $url;
        } else {
            return $url;
        }
    }

    /**
     * 本頁開始條數
     * @return int
     */
    private function star() {
        if ($this->total == 0) {
            return 0;
        } else {
            return ($this->page - 1) * $this->pageSize + 1;
        }
    }

    /**
     * 本頁結束條數
     * @return type
     */
    private function end() {
        return min($this->page * $this->pageSize, $this->total);
    }

    /**
     * 設置當前頁大小
     * @return type
     */
    private function setPageSize() {
        return $this->end() - $this->star() + 1;
    }

    /**
     * 首頁
     * @return type
     */
    private function frist() {
        $html = '';
        if ($this->page == 1) {
            $html .= $this->replace("{$this->uri}&page=1", $this->config['frist'], true);
        } else {
            $html .= $this->replace("{$this->uri}&page=1", $this->config['frist'], false);
        }
        return $html;
    }

    /**
     * 上一頁
     * @return type
     */
    private function prev() {
        $html = '';
        if ($this->page > 1) {
            $html .= $this->replace($this->uri.'&page='.($this->page - 1), $this->config['pre'], false);
        } else {
            $html .= $this->replace($this->uri.'&page='.($this->page - 1), $this->config['pre'], true);
        }
        return $html;
    }

    /**
     * 分頁數字列表
     * @return type
     */
    private function pagelist() {
        $linkpage = "";
        $lastlist = floor($this->listnum / 2);
        for ($i = $lastlist; $i >= 1; $i--) {
            $page = $this->page - $i;
            if ($page >= 1) {
                $linkpage .= $this->replace("{$this->uri}&page={$page}", $page, false);
            } else {
                continue;
            }
        }
        $linkpage .= $this->replace("{$this->uri}&page={$this->page}", $this->page, true);
        for ($i = 1; $i <= $lastlist; $i++) {
            $page = $this->page + $i;
            if ($page <= $this->pageNum) {
                $linkpage .= $this->replace("{$this->uri}&page={$page}", $page, false);
            } else {
                break;
            }
        }
        return $linkpage;
    }

    /**
     * 下一頁
     * @return type
     */
    private function next() {
        $html = '';
        if ($this->page < $this->pageNum) {
            $html .= $this->replace($this->uri.'&page='.($this->page + 1), $this->config['next'], false);
        } else {
            $html .= $this->replace($this->uri.'&page='.($this->page + 1), $this->config['next'], true);
        }
        return $html;
    }

    /**
     * 最後一頁
     * @return type
     */
    private function last() {
        $html = '';
        if ($this->page == $this->pageNum) {
            $html .= $this->replace($this->uri.'&page='.($this->pageNum), $this->config['last'], true);
        } else {
            $html .= $this->replace($this->uri.'&page='.($this->pageNum), $this->config['last'], false);
        }
        return $html;
    }

    /**
     * 跳轉按鈕
     * @return string
     */
    private function gopage() {
        $html = '';
        $html.='&nbsp;<input type="text" value="' . $this->page . '" οnkeydοwn="javascript:if(event.keyCode==13){var page=(this.value>' . $this->pageNum . ')?' . $this->pageNum . ':this.value;location=\'' . $this->uri . '&page=\'+page+\'\'}" style="width:25px;"/><input type="button" οnclick="javascript:var page=(this.previousSibling.value>' . $this->pageNum . ')?' . $this->pageNum . ':this.previousSibling.value;location=\'' . $this->uri . '&page=\'+page+\'\'" value="GO"/>';
        return $html;
    }

    /**
     * 模板替換
     * @param type $replace     替換內容
     * @param type $result      條件
     * @return type
     */
    private function replace($url, $text, $result = true) {
        $template = ($result ? $this->activeTemplate : $this->notActiveTemplate);

         $html = str_replace('{url}', $url, $template);
         $html = str_replace('{text}', $text, $html);
        return $html;
    }
}

很隨意的寫出來的

<?php
/**
 * Created by PhpStorm.
 * User: zerodeng
 * Date: 15-5-12
 * Time: 下午4:09
 */

class pagination {

    private $total;
    private $per_page;
    private $link;
    private $page;
    private $page_offset;
    private static $instance;

    public function __construct(){
        $this->per_page = 40;
    }

    public static function get_instance(){
        if(!isset(self::$instance)){
            self::$instance = new self;
        }
        return self::$instance;
    }

    public function set_total($num){
        $this->total = $num;
    }

    public function set_link($link=''){
        if($link){
            $this->link = $link.'?page=';
        }else{
            $this->link = $_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF'].'?page=';
        }
    }

    public function set_page(){
        if(!empty($_GET['page'])){
            $this->page = $_GET['page'];
        }else{
            $this->page = 1;
        }
    }

    public function set_page_offset(){
        if(isset($this->page)){
            $this->page_offset = ($this->page-1)*$this->per_page;
        }
    }

    public function page_limit($mode=''){
        $this->set_page();
        $this->set_page_offset();
        if($mode == 'str'){
            $limit = $this->page_offset.','.$this->per_page;
            return $limit;
        }
        $limit = array($this->page_offset,$this->per_page);
        return $limit;
    }

    public function show_page($page_num=5){
        if(!isset($this->page)){
            $this->set_page();
        }
        $first_page = 1;
        $last_page = ceil($this->total/$this->per_page);
        if(!isset($this->link)){
            $this->set_link();
        }
        $html = '';
        $html .= '<div id="show_page">總共'.$this->total.'條記錄 '.$this->page.'/'.$last_page;
        if($this->page != $first_page){
            $html .= '<a href="http://'.$this->link.$first_page.'">首頁</a>&nbsp';
        }
        if($page_num>=$last_page){
            for($i = 1;$i<=$last_page;$i++){
                $html .= '|&nbsp<a href="http://'.$this->link.$i.'">'.$i.'</a>&nbsp';
            }
        }else{
            $page_offset = $this->page+$page_num;
            if($page_offset<$last_page){
                for($i=$this->page;$i<=($this->page+$page_num);$i++){
                    $html .= '|&nbsp<a href="http://'.$this->link.$i.'">'.$i.'</a>&nbsp';
                }
            }else{
                for($i=$this->page;$i<=$last_page;$i++){
                    $html .= '|&nbsp<a href="http://'.$this->link.$i.'">'.$i.'</a>&nbsp';
                }
            }

        }
        if($this->page != $last_page){
            $html .= '<a href="http://'.$this->link.$last_page.'">最後一頁</a>&nbsp';
        }
        $html .= '</div>';
        return $html;
    }

}

又是一個隨便寫的分頁類!看原理,很強大

<?php
    class page
    {
        private $pagesize;
        private $lastpage;
        private $totalpages;
        private $nums;
        private $numPage=1;

        function __construct($page_size,$total_nums)
        {
            $this->pagesize=$page_size;      //每頁顯示的數據條數
            $this->nums=$total_nums;     //總的數據條數
            $this->lastpage=ceil($this->nums/$this->pagesize);     //最後一頁
            $this->totalpages=ceil($this->nums/$this->pagesize);   //總得分頁數
            if(!empty($_GET[page]))
            {
                $this->numPage=$_GET[page];
                if(!is_int($this->numPage))  $this->numPage=(int)$this->numPage;
                if($this->numPage<1)  $this->numPage=1;
                if($this->numPage>$this->lastpage) $this->numPage=$this->lastpage;
            }
        }

        function show_page_result()
        {
            $row_num=(($this->numPage)-1) * $this->pagesize; //表示每一頁從第幾條數據開始顯示
            $row_num=$row_num.",";
            $SQL="SELECT * FROM `test` LIMIT $row_num $this->pagesize";
            $db=new database();
            $query=$db->execute($SQL);
            while($row=mysql_fetch_array($query))
            {
                echo "<b>".$row[name]." | ".$row[sex]."<hr>";
            }
            $db=null;
        }

        function show_page_way_1()  //以"首頁 上一頁 下一頁 尾頁"形式顯示
        {
            $url=$_SERVER["REQUEST_URI"];
            $url=parse_url($url);   //parse_url -- 解析 URL,返回其組成部分,注: 此函數對相對路徑的 URL 不起作用。
            $url=$url[path];
            if($this->nums > $this->pagesize)      //判斷是否滿足分頁條件
            {
                echo " 共 $this->totalpages 頁 當前爲第<font color=red><b>$this->numPage</b></font>頁 共 $this->nums 條 每頁顯示 $this->pagesize 條";
                if($this->numPage==1)
                {
                    echo " 首頁 ";
                    echo "上一頁 ";
                }
                if($this->numPage >= 2 && $this->numPage <= $this->lastpage)
                {
                    echo " <a href=$url?page=1>首頁</a> " ;
                    echo "<a href=$url?page=".($this->numPage-1).">上一頁</a> " ;
                }

                if($this->numPage==$this->lastpage)
                {
                    echo "下一頁 ";
                    echo "尾頁<br>";
                }
                if($this->numPage >= 1 && $this->numPage < $this->lastpage)
                {
                    echo "<a href=$url?page=".($this->numPage+1).">下一頁</a> ";
                    echo "<a href=$url?page=$this->lastpage>尾頁</a><br> ";
                }
            }
            else    return;
        }

        function show_page_way_2()      //以數字形式顯示"首頁 1 2 3 4 尾頁"
        {
            $url=$_SERVER["REQUEST_URI"];
            $url=parse_url($url);   //parse_url -- 解析 URL,返回其組成部分,注: 此函數對相對路徑的 URL 不起作用。
            $url=$url[path];
            if($this->nums > $this->pagesize)
            {
                if($this->numPage==1)    echo "首頁";
                else    echo "<a href=$url?page=1>首頁</a>";
                for($i=1;$i<=$this->totalpages;$i++)
                {
                    if($this->numPage==$i)
                    {
                        echo " ".$i." ";
                    }
                    else
                    {
                        echo " <a href=$url?page=$i>$i</a> ";
                    }

                }
                if($this->numPage==$this->lastpage)       echo "尾頁";
                else    echo "<a href=$url?page=$this->lastpage>尾頁</a>";
            }
        }

        function show_page_way_3()
        {
            global $c_id;
            $url=$_SERVER["REQUEST_URI"];
            $url=parse_url($url);   //parse_url -- 解析 URL,返回其組成部分,注: 此函數對相對路徑的 URL 不起作用。
            $url=$url[path];
            if($this->nums > $this->pagesize)      //判斷是否滿足分頁條件
            {
                if($c_id)
                {
                    echo "到第<select name='select1' onChange=\"location.href='$url?c_id=$c_id&page='+this.value+'&pagesize=$this->pagesize'\">";
                }
                else    echo "到第<select name='select1' onChange=\"location.href='$url?page='+this.value+'&pagesize=$this->pagesize'\">";
                for($i = 1;$i <= $this->totalpages;$i++)
                echo "<option value='" . $i . "'" . (($this->numPage == $i) ? 'selected' : '') . ">" . $i . "</option>";
                echo "</select>頁, 每頁顯示";
                if($c_id)
                {
                    echo "<select name=select2 onChange=\"location.href='$url?c_id=$c_id&page=$this->numPage&pagesize='+this.value+''\">";
                }
                else    echo "<select name=select2 onChange=\"location.href='$url?page=$this->numPage&pagesize='+this.value+''\">";
                for($i = 0;$i < 5;$i++) // 將個數定義爲五種選擇
                {
                    $choice= ($i+1)*4;
                    echo "<option value='" . $choice . "'" . (($this->pagesize == $choice) ? 'selected' : '') . ">" . $choice . "</option>";
                }
                echo "</select>個";
            }
            else    return;     //echo "沒有下頁了";

        }





    }


?>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章