Categories: PHP | Tags: , | Views: 1,573

 

写了一个功能相对比较全面的php分页类,包括两种分页模式,两种底部链接显示模式,可以进行任意搭配, 另外还包括服务端和客户端排序.

其中对数据库的操作采用的是这个类. 需要对$db按自己的实际情况进行实例化.

客户端排序需要jquery.js库文件和jquery.tablesorter.js文件.

先看两种分页模式的效果图:

paginate


 

paginate1



第一种模式的调用代码:

1
2
3
4
5
6
7
8
9
10
11
12
            function show_del($id){
                return "<input type=button value=$id>";    
            }
            $pagination = new paginate(array(
                sql     => 'SELECT * FROM `dishes`',
                theader    => 'ID,Dish_name,Dish_price,Dish_Dir,Manipulation',
                tbody    => '<tr><td>{var:dish_id}</td><td>{var:dish_name}</td><td>{var:dish_sm_price}</td><td>{var:dish_dir}</td><td>{var:dish_id;fun:show_del}</td></tr>',
                linkmode => 1,
                orderbys => 'dish_id:ID;dish_name:NAME;dish_sm_price:PRICE',
                clientsort => 1
            ));    
            $pagination->show();

第二种模式的调用代码:

1
2
3
4
5
6
7
8
9
10
11
12
            function show_del($id){
                return "<input type=button value=$id>";    
            }
            $pagination = new paginate(array(
                sql     => 'SELECT * FROM `dishes`',
                theader    => 'ID,Dish_name,Dish_price,Dish_Dir,Manipulation',
                tbody => '<div>dish_id:{var:dish_id}<br>dish_name:{var:dish_name}<br>dish_price:{var:dish_sm_price}</div>',
                mode =>1,
                orderbys => 'dish_id:ID;dish_name:NAME;dish_sm_price:PRICE',
                clientsort => 1
            ));    
            $pagination->show();

类的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
class paginate{
    var $data = array();    // data show in this page
    var $count;                // total count of the records
    var $page;                // page number of this page
    var $sql;                // total records sql, including 'order by' clause
    var $limit = 12;        // how many records to show in this page
    var $mode = 0;            // 2 modes, 0 for one record in one line with headers; 
                            //          1 for multiple records in one line without headers
    var $theaders;            // headers for mode 0, like "ID,姓名,电话,..."
    var $tbody;                // cycle body
                            // for mode 0, $tbody is like "<tr><td>{var:id;fun:fun1}</td>...<td>{var:value;fun:fun2}</td></tr>"
                            // for mode 1, $tbody is like "<div>{var:id;fun:fun1}</div>"
    var $rnpl = 4;            // Records Number Per Line, just for mode 1.
    var $linkmode = 0;        // temporarily 2 like modes. One displays page numbers by combo box; another displays them directly.
    var $rnthis;            // Records Number in THIS page. It equals to $limit, but probably not in the last page.
    var $colnames = array();// colomn names in this table
    var $pagenum;            // total page number
    var $maxpagenum = 11;    // for linkmode 1, how many page numbers to show, odd number required    
    var $tableid = 'paginate_table';
    var $orderbys;            // "id:序号;name:姓名;phone:电话"
    var $orderby;
    var $rank = 'ASC';
    var $clientsort = 0;    // close client sort as default
    function paginate($opts){
        global $db;            // ensure include db.class.php
        $this->sql        = $opts['sql'];
        $theader        = $opts['theader'];
        $this->theaders = split(',',$theader);
        $this->tbody    = $opts['tbody'];
        $this->page     = $_GET['page'];
        if($opts['limit'])        $this->limit    = $opts['limit'];
        if($opts['mode'])        $this->mode        = $opts['mode'];
        if($opts['rnpl'])        $this->rnpl        = $opts['rnpl'];
        if($opts['linkmode'])    $this->linkmode    = $opts['linkmode'];
        if(!$this->page)         $this->page     = 1;
        $this->count     = $db->num_rows($this->sql);
        $this->pagenum = ceil($this->count/$this->limit);
        if($this->page < 1) $this->page = 1;
        if($this->page > $this->pagenum) $this->page = $this->pagenum;
        if($opts['orderbys'])$this->orderbys = $opts['orderbys'];
        if($this->orderbys){
            $this->sql = preg_replace('/order\s+by\s+.+(?:\s+(?:a)|(?:de)sc)?/i','',$this->sql);
            $getorderby = split(' ',$_GET['orderby']);
            if($getorderby[0]) $this->orderby = $getorderby[0];
            else { 
                $obs = split(':',$this->orderbys);
                $this->orderby = $obs[0];
            }
            if($getorderby[1]) $this->rank = $getorderby[1];
            $this->sql .= " ORDER BY `".$this->orderby."` ".$this->rank;
        }
        $thissql        = $this->sql." limit ".($this->page-1)*$this->limit.",".$this->limit;
        $this->data     = $db->fetch_all($thissql);
        $this->rnthis    = $db->num_rows($thissql);
        preg_match_all("/\{var:(.+?)(;fun:.+?)?\}/",$this->tbody,$matches);
        $this->colnames    = $matches[1];
        if($opts['maxpagenum'])$this->maxpagenum = $opts['maxpagenum'];
        if($opts['tableid'])$this->tableid = $opts['tableid'];
        if($opts['clientsort'])$this->clientsort = $opts['clientsort'];
    }
 
    function getHeaders(){
        if(!$this->mode){
            $headers_str = "<thead><tr>";
            foreach ($this->theaders as $h){
                $headers_str .= "<th>$h</th>";    
            }
            $headers_str .= "</tr></thead>\n";
            return $headers_str;
        }
        return '';
    }
 
    function show(){
        $show_str = "";
        if($this->orderbys){
            $show_str .= "排序依据:   ";
            $orderbyss = split(';',$this->orderbys);
            foreach ($orderbyss as $ob){
                preg_match("/^(.+?)\:(.+)$/",$ob,$matches);    
                if($this->orderby == $matches[1]){
                    $show_str .= $this->getLink("orderby",$this->orderby." ".($this->rank=='ASC'?'DESC':'ASC'),$matches[2].($this->rank=='ASC'?'↑':'↓'),"title=按".$matches[2].($this->rank=='ASC'?'降':'升')."序排列")."   ";
                } else {
                    $show_str .= $this->getLink("orderby",$matches[1]." ASC",$matches[2].'☆',"title=按".$matches[2]."升序排列")."   ";
                }
            }
        }
        $show_str .= '<table id="'.$this->tableid.'" cellspacing=1 '.($this->clientsort?'clientsort=1':'').'>';
        if($this->mode){
            $show_str .= '<tbody>';
            for($i=0; $i<ceil($this->rnthis/$this->rnpl); $i++){
                $show_str .= "<tr>";
                for($j=0; $j<$this->rnpl; $j++){  // ---------
                    $show_str .= "<td>";
                    $body = $this->tbody;
                    for($k=0; $k<count($this->colnames); $k++){
                        $body = preg_replace("/\{var:(".preg_quote($this->colnames[$k]).")(;fun:.+?)?\}/","{var:".$this->data[$i*$this->rnpl+$j][$this->colnames[$k]]."$2}",$body);
                    }
                    if($j < $this->rnthis-$i*$this->rnpl) $show_str .= preg_replace("/\{var:([\s\S]+?)(?:;fun:(.+?))?\}/e","$2('$1')",$body);
                    $show_str .= "</td>";    
                }
                $show_str .= "</tr>";
            }
        } else {
            $show_str .= $this->getHeaders();
            $show_str .= '<tbody>';
            for($j=0; $j<$this->rnthis; $j++){  // ---------
                $body = $this->tbody;
                for($k=0; $k<count($this->colnames); $k++){
                    $body = preg_replace("/\{var:(".preg_quote($this->colnames[$k]).")(;fun:.+?)?\}/","{var:".$this->data[$j][$this->colnames[$k]]."$2}",$body);
                }
                $show_str .= preg_replace("/\{var:([\s\S]+?)(?:;fun:(.+?))?\}/e","$2('$1')",$body);
            }
        }
        $show_str .= '</tbody>';
        $show_str .= $this->getLinks();
        $show_str .= '</table>';
        echo $show_str;
    }
 
    function getHref($parms, $values){
        $ps = $_GET;
        if(is_array($parms)){
            for($i=0; $i<count($parms); $i++){
                $ps[$parms[$i]] = $values[$i];
            }
        } else {
            $ps[$parms] = $values;
        }
        $link = $_SERVER['PHP_SELF']."?";
        foreach ($ps as $k => $v){
            $link .= $k."=".urlencode($v)."&";
        }
        if(substr($link,-1) == "&") $link = substr($link,0,-1);
        return $link;        
    }
 
    function getLink($parms, $values, $str="", $attr = ""){
        return "<a href='".$this->getHref($parms, $values)."' $attr>$str</a>";
    }
 
    function getLinks(){
        $links_str = "<tfoot><tr><td colspan=".($this->mode?$this->rnpl:count($this->theaders))." style='text-align:center'>";
        if(!$this->linkmode) $links_str .= "第".(($this->page-1)*$this->limit+1)."~".(($this->page-1)*$this->limit+$this->rnthis)."条/共".$this->count."条记录 ";
        $links_str .= "[".($this->page>1?$this->getLink("page",1,"首页"):"首页")."] ";
        $links_str .= "[".($this->page>1?$this->getLink("page",$this->page-1,"上页"):"上页")."] ";
        if($this->linkmode){
            if($this->pagenum <= $this->maxpagenum){
                for($i=1; $i<=$this->pagenum; $i++){
                    if($this->page == $i) $links_str .= $this->getLink("page",$i,$i,"class=thispage")." ";
                    else $links_str .= $this->getLink("page",$i,$i)." ";
                }
            } else {
                if($this->page <= ($this->maxpagenum+1)/2) $startnum = 1;
                else $startnum = $this->page - ($this->maxpagenum+1)/2 + 1;
                if($this->pagenum - $this->page < ($this->maxpagenum+1)/2) $endnum = $this->pagenum;
                else $endnum = $this->page + ($this->maxpagenum+1)/2 - 1;
                if($startnum > 1){
                    $links_str .= $this->getLink("page",$startnum-1,"...");
                }
                for($i=$startnum; $i<=$endnum; $i++){
                    if($this->page == $i) $links_str .= $this->getLink("page",$i,$i,"clas=thispage")." ";
                    else $links_str .= $this->getLink("page",$i,$i)." ";
                }
                if($endnum < $this->pagenum){
                    $links_str .= $this->getLink("page",$endnum+1,"...");
                }
            }
        }
        $links_str .= "[".($this->page<$this->pagenum?$this->getLink("page",$this->page+1,"下页"):"下页")."] ";
        $links_str .= "[".($this->page<$this->pagenum?$this->getLink("page",$this->pagenum,"尾页"):"尾页")."] ";
        if(!$this->linkmode){
            $links_str .= "第<select onchange=\"javascript:location='".$this->getHref("page","")."'.replace('page=','page='+this.value)\">\n";
            for($i=1; $i<=$this->pagenum; $i++){
                if($i == $this->page) $links_str .= "<option value=".$i." selected>".$i."</option>\n";
                else $links_str .= "<option value=".$i." >".$i."</option>\n";    
            }
            $links_str .= "</select>页/";
        }
        $links_str .= "共".$this->pagenum."页</td></tr></tfoot>";
        return $links_str;
    }
}

样式设置js(需要先引用jquery.js)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
function setpaginatestyle(paginate_table_id){
    if(paginate_table_id == undefined) paginate_table_id = '#paginate_table';
    pbody = paginate_table_id + '>tbody>';
    phead = paginate_table_id + '>thead>';
    pfoot = paginate_table_id + '>tfoot>';
    var tablebordercolor = '#5d7e49';
    var tdheight = '24px';
    var tdpadding = '2px';
    var oddtrbgcolor = '#b4bcaf';
    var eventrbgcolor = '#fff';
    var overtrbgcolor = '#dedfdd';
    var thbgcolor = '#8b9f7f';
    var thcolor = '#fff';
    var footerbgcolor = '#fff';
    var footeraborder = '1px 3px 1px 3px';
    var tablewidth = '450px';
    $(paginate_table_id).css({
        'background-color':tablebordercolor,
        'width':tablewidth
    });
    $(pbody+'tr>td').add(phead+'tr>th').add(pfoot+'tr>td').css({
        'padding':tdpadding,
        'height':tdheight
    });
    $(phead+'tr').css({
        'background-color':thbgcolor,
        'color':thcolor
    });
 
    $(pbody+'tr:odd')
                    .css('background-color',oddtrbgcolor)
                    .hover(
        function(){
            $(this).css({'background-color':overtrbgcolor});    
        },
        function(){
            $(this).css({'background-color':oddtrbgcolor});
        }        
    );
    $(pbody+'tr:even')
                     .css('background-color',eventrbgcolor)
                     .hover(
        function(){
            $(this).css('background-color',overtrbgcolor);    
        },
        function(){
            $(this).css('background-color',eventrbgcolor);
        }        
    );        
    $(pfoot+'tr').css('background-color',footerbgcolor).unbind();
    $(pfoot+'tr a').css('padding',footeraborder);
    $(pfoot+'tr a.thispage').css({
        'background-color':oddtrbgcolor,
        'border':'1px solid '+tablebordercolor
    });
    if($(paginate_table_id).attr('clientsort')){
        $('head').append('<script language="javascript" src="js/jquery.tablesorter.js"></script>');
        $(paginate_table_id).tablesorter();
    }
}
 
$(document).ready(function(){
    setpaginatestyle();    
});

 

这篇文章来自 迷途知返(PWWANG.COM), 转载请注明出处。 版权说明

  1. 小肜
    June 17th, 2009 at 21:01
    Reply | Quote | #1

    无意中登洋洋的QQ,不知道叫你啥?看过后感觉自己太菜了

    大学两年咯 真的发现自己学的实在太少了

    • June 19th, 2009 at 14:04
      Quote | #2

      噢,我是他表哥,你可以问他

  2. hihello2010
    February 14th, 2010 at 21:01
    Reply | Quote | #3

    hi,hello:
    节日愉快!

    写的很好! ;)
    请问能否给传过来一个完整的实例?
    $(paginate_table_id).tablesorter(); } } 这一句总是过不去.

    谢谢
    我的邮箱: hihello2010@yahoo.cn ;)

  3. hihello
    February 16th, 2010 at 20:31
    Reply | Quote | #4

    嗨!

    仔细看了一遍代码,终于调通了!

    谢谢!

    祝好!

  4. hihello
    February 23rd, 2010 at 11:25
    Reply | Quote | #5

    请问您的联系邮箱?发到我的邮箱好么?沟通点事情!

    谢谢

;) :| :x :twisted: :roll: :oops: :o :mrgreen: :lol: :idea: :evil: :cry: :arrow: :P :D :?: :? :) :( :!: 8O 8)

你可以使用@somebody:开头, 来邮件通知somebody你回复了他的留言(用户名区分大小写).