Correction status:qualified
Teacher's comments:
查询数据分页:
<?php //设置配置项 $config = [ 'sql_type' => 'mysql', 'host'=>'localhost', 'user'=>'abc', 'pwd'=>'abc', 'db_name'=>'test', ]; //分页类 class Page{ private $pdo; private $page_num = 20;//每页显示几条 private $tag_count = 8;//设置一页标签链接数目 private $currentPage=1;//当前页 private $start_num;//页码起始页 private $total_page;//共几页 private $total_data;//共几条数据 private $table;//当前操作表 function __construct($arr,$table){ try { $this->pdo = new PDO("{$arr['sql_type']}:host={$arr['host']};dbname={$arr['db_name']}",$arr['user'],$arr['pwd']); } catch (\PDOException $e) { die($e->getMessage()); } $this->table=$table; //统计表共有几条数据 $sql = "SELECT count(*) FROM {$this->table}"; $stmt = $this->pdo->prepare($sql); $stmt->execute(); $res = $stmt->fetchColumn(); $this->total_data = $res; //统计分页后总共会有几页 $this->total_page = ceil($res/$this->page_num); } function __get($name){ //当访问当前页数大于总页数的时候,返回最大页数 if($name=='currentPage' && $this->currentPage > $this->total_page){ return $this->total_page; } elseif (!isset($this->$name)) { return "错误"; } return $this->$name; } //返回当前页数据 function get_list(){ //设置当前页currentPage if (empty($_GET['p']) || $_GET['p']>$this->total_page) { $p =1; }else{ $p = $_GET['p']; } $this->currentPage = $p; //调用防范,找出第一个数字是哪个 $this->get_startnum(); $offset = ($p-1)*$this->page_num; //查询当前的数据 $sql = "SELECT * FROM {$this->table} LIMIT {$offset},{$this->page_num}"; $stmt = $this->pdo->prepare($sql); $stmt->execute(); return $stmt->fetchAll(PDO::FETCH_ASSOC); } //返回列表标签起始页数,判断页码列表第一个数从哪里开始,判断条件是显示几个数字 function get_startnum(){ $now = $this->currentPage;//当前页 $tag_count = $this->tag_count;//要显示几个数字 $total_page = $this->total_page;//总页码数 $num = ceil($tag_count/2); if($now <= $num){ $start_num =0; } elseif ($now>($total_page-$num)) { $start_num = $total_page-$num*2+1; }else{ $start_num = $now-$num; } $this->start_num = $start_num; } } $page = new Page($config,'user'); // var_dump($page->get_list()); ?> <table> <tr> <td>序号</td> <td>名字</td> <td>密码</td> </tr> <?php foreach ($page->get_list() as $k => $v): ?> <tr> <td><?=($k+1)?></td> <td><?=$v['name']?></td> <td><?=$v['pwd']?></td> </tr> <?php endforeach ?> </table> <div> 共<?=$page->total_data?>条数据,共<?=$page->total_page?>页,当前为<?=$page->currentPage?>页 <br> <?php //如果是第前几页,则把上一页取消掉 echo ($page->currentPage==1)?"没有了":"<a href='/index.php?p=".($page->currentPage-1)."'>上一页</a>"; ?> <?php for ($i=1; $i <=$page->tag_count; $i++) { $a =$page->start_num+$i; //如果为当前页则输出文字,如果不是则输出连接 if ($a==$page->currentPage) { echo $a; }else{ echo "-<a href='/index.php?p=".$a."'>$a</a>-"; } } ?> <?php //如果是最后一页,则把下一页取消掉 echo ($page->currentPage==$page->total_page)?"没有了":"<a href='/index.php?p=".($page->currentPage+1)."'>下一页</a>"; ?> <form action="/index.php" method="get"> <input type="text" name="p" width="50" placeholder="请输入页码"> <button>跳转</button> </form> </div>
点击 "运行实例" 按钮查看在线实例