Correcting teacher:PHPz
Correction status:qualified
Teacher's comments:
<?php
/***
* $page 当前页
* $pageSize 每页显示条数
* $pages 总页数
*/
function page($page,$pageSize,$pages){
$span=''; //定义空字符串
$preStr =''; //上一页
$nextStr= ''; //下一页
for($i=1;$i<=$pages;$i++){
$active=($page==$i)?'active':null;
$span .= '<a class="'.$active.'" href="?p='.$i.'">'.$i.'</a>';
}
$prev = $page - 1;
if($page<=1) $prev==1;
if($page>1){
$preStr = '<a href="?p='.$prev.'">上一页</a>';
}
$next = $page + 1;
if($page>=$pages) $next=$pages;
if($page<$pages){
$nextStr ='<a href="?p='.$next.'">下一页</a>';
}
$span = $preStr.$span.$nextStr;
return $span;
}
获取数据
$page=$_GET['p']??1;
$page = $page<1?1:$page;
//每页显示条数
$pageSize=10;
//偏移量
$offset = ($page - 1) * $pageSize;
$pdo = new PDO('mysql:dbname=guer', 'root', 'root',[PDO::ATTR_ERRMODE=>PDO::ERRMODE_WARNING]);
$sql = 'select * from auth_rule limit ?,? ';
$stmt = $pdo->prepare($sql);
$stmt->bindParam('1',$offset,PDO::PARAM_INT);
$stmt->bindParam('2',$pageSize,PDO::PARAM_INT);
$stmt->execute();
$lists = $stmt->fetchAll(PDO::FETCH_ASSOC);
// 计算总记录数 $total
$sql = 'SELECT count(id) AS TOTAL FROM auth_rule';
$stmt = $pdo->prepare($sql);
$stmt->execute();
$total = $stmt->fetch(PDO::FETCH_ASSOC)['TOTAL'];
//总页数= 总行数/每页显示行数
$pages = ceil($total / $pageSize); //取整数,ceil()进一法取整
实现分页
<?=page($page,$pageSize,$pages);?>
获取数据
namespace redis_demo;
use Redis, PDO;
if (extension_loaded('redis')) {
$redis = new Redis();
$redis->connect('127.0.0.1', '6379');
// 对于不经常更新的且数据量大的sql查询结果做存储、
$lists = (new PDO('mysql:dbname=guer', 'root', 'root'))->query('select * from auth_rule')->fetchAll(PDO::FETCH_ASSOC);
$lists = json_encode(getTree($lists), 320);
$redis->set('cates', $lists);
}
// 返回平面化且有关系的无限极分类
function getTree($list, $pid = 0, $level = 0)
{
static $tree = [];
foreach ($list as $row) {
if ($row['pid'] == $pid) {
$row['level'] = $level;
$tree[] = $row;
getTree($list, $row['id'], $level++);
}
}
return $tree;
}
获取分页需要的基本参数
$redis = new Redis(); // 创建对象
$redis->connect('127.0.0.1','6379');
$lists = json_decode($redis->get('cates'),true);
//提供分页数据
//当前页
$page = $_GET['p']??1;
//越界检测
$page = $page<1?1:$page;
//每页显示行数
$pageSize = 20;
//偏移量
$offset = ($page - 1)*$pageSize; // (当前页-1)*每页显示数
// 总页数
$pages = ceil(count($lists)/$pageSize);
$lists = array_splice($lists, $offset, $pageSize);
实现分页
<?=page($page,$pageSize,$pages);?>