even

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

1、利用bootstrap的css框架的前提下,封装个Php的分页框架

命名为test.php,具体代码如下

 1 <?php
 2 class Pagination
 3 {
 4     private $cfg;
 5     private $content = '';                        //分页导行条内容部份
 6 
 7     public function __construct($config = null){
 8         $this->cfg = array_replace([
 9             'count' => 0,                                                       //总的数据数量
10             'pageSize' => 10,                                                   //每次数据的数量
11             'currentPage' => $_GET['page'] ?? 1,                                //当前所在的页码
12             'scope' => 3,                                                       //显示前面几条后面几条
13             'dir' => sprintf('./%s', basename($_SERVER['PHP_SELF']))    //请求的地址
14         ], $config ? $config : []);
15     }
16 
17     /**获取总的页数
18      * @return float
19      */
20     private function getPageCount() {
21         return ceil($this->cfg['count'] / $this->cfg['pageSize']);
22     }
23 
24     /**获取分页链接的地址
25      * @param int $num
26      * @return string
27      */
28     private function getRealDir(int $num) {
29         return $this->cfg['dir']."?page={$num}";
30     }
31 
32     /**获取分页的最大值和最小值
33      * @param int $MaxPage 最大的页数
34      * @return array
35      */
36     private function getLimitScope(int $MaxPage) {
37         $arr = [];
38         $current = $this->cfg['currentPage'];
39         $step = $this->cfg['scope'];
40         $arr[0] = $current - $step <= 1? 1: $current - $step;
41         $arr[1] = $current + $step >= $MaxPage? $MaxPage: $current + $step;
42         return $arr;
43     }
44 
45     /**生成分页的主体部份
46      * @return string
47      */
48     private function getContent() {
49         $count = $this->getPageCount();
50         $this->cfg['currentPage'] > $count? $this->cfg['currentPage'] = 1: null;   //当如果当前页大于最大页要进行规避错误
51         $wrap = '<ul class="pagination"><li><a href="%s">&laquo;</a></li>%s<li><a href="%s">&raquo;</a></li></ul>';
52         list($begin_num, $end_num) = $this->getLimitScope($count);
53         for($i=$begin_num; $i<=$end_num; $i++) {
54             $this->content .= sprintf('<li class="%s"><a href="%s">%d</a></li>', $this->cfg['currentPage'] == $i? 'active': '',$this->getRealDir($i), $i);
55         }
56         $start = $this->getRealDir($this->cfg['currentPage'] <= 1? 1: $this->cfg['currentPage']-1);
57         $end = $this->getRealDir($this->cfg['currentPage']>= $count? $count: $this->cfg['currentPage'] + 1);
58         return sprintf($wrap, $start, $this->content, $end);
59     }
60 
61     /**分页组件的初始化
62      * @return string
63      */
64     public function init() {
65         return $this->getContent();
66     }
67 }
68 
69 ?>

2、利用之前封装的操作数据库的单例方法(假如命名为index.php)

 1 <?php
 2 header('content-type:text/html;charset=utf-8');
 3 ini_set('display_errors', true);
 4 $config = [
 5     'host' => 'localhost',
 6     'user' => 'root',
 7     'password' => '*****',
 8     'dbname' => 'learn',
 9     'port' => 3306,
10     'charset' => 'utf8'
11 ];
12 
13 final class DB {
14     private static $mysqli;
15     private function __clone() {}
16     private function __construct() {
17         global $config;
18         $mysqli = new Mysqli($config['host'], $config['user'], $config['password'], $config['dbname'], $config['port']);
19         if($mysqli->connect_errno) {
20             die('数据库连接错误'.$mysqli->connect_error);
21         }
22         $mysqli->set_charset($config['charset']);
23         self::$mysqli = $mysqli;
24     }
25 
26     public static function getInstance() {
27         if(!self::$mysqli instanceof self) {
28             new self();
29         }
30         return self::$mysqli;
31     }
32 }
33 ?>

3、具体的页面操作方法如下(假如定义为page.php)

 1 <!doctype html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Document</title>
 6     <link href="./resource/bootstrap.css" rel="stylesheet">
 7 </head>
 8 <body>
 9 <div class="container">
10     <?php
11         require_once('test.php');
12         require_once('index.php');
13         $mysqli = DB::getInstance();
14         $total_sql = "SELECT COUNT(*) AS `total` from `goods`";
15         $total = ($mysqli-> query($total_sql))->fetch_assoc();
16 
17         $pageSize = 6;
18         $arr = [];
19         $res_str = sprintf('select * from `goods` limit %d offset %d', $pageSize, (($_GET['page'] ?? 1)-1)*$pageSize);
20         $res = $mysqli->query($res_str);
21         while($row = $res->fetch_assoc()) {
22             array_push($arr, $row);
23         }
24         $res->free();
25         $mysqli->close();
26 
27         $p = new Pagination([
28             'count' => $total['total'],
29             'pageSize' => $pageSize
30         ]);
31         echo $p->init();
32     ?>
33     <table class="table table-bordered table-hover table-striped">
34         <?php foreach($arr as $key=>$val):?>
35             <tr>
36                 <td><?= $val['goods_id']?></td>
37                 <td><?= $val['goods_sn']?></td>
38                 <td><?= $val['goods_name']?></td>
39                 <td><?= $val['goods_number']?></td>
40                 <td><?= $val['market_price']?></td>
41                 <td><?= $val['shop_price']?></td>
42                 <td><?= date('Y-m-d H:i:s',$val['add_time'])?></td>
43             </tr>
44         <?php endforeach;?>
45     </table>
46 </div>
47 </body>
48 </html>

以上即可实现分页的效果!

posted on 2019-05-26 00:16  even_blogs  阅读(492)  评论(0编辑  收藏  举报