分页效果
效果展示
1.控制器实现分页查询
public function index(Article $article)
{
$page = $this->request->get('page', 1); //当前页码
$size = 3; //定义每页显示的条数
$offset = ($page - 1) * $size; // 计算开始位置
$data = $article->orderBy('id', 'DESC')->limit($offset, $size)->get([
'id', 'title', 'author', 'show', 'views', 'created_at'
]);
$this->assign('article', $data);
$total = $article->count();
$this->assign('page_html', Page::html('?page=', $total, $page, $size));
//$page_html = Page::html('?page=', $total, $page, $size);
//$this->assign($page_html, $page_html);
return $this->fetch('admin/article_list');
}
2.创建一个Page类
class Page
{
public static function html($url, $total, $page, $size, $num = 5)
{
$page = max((int)$page, 1); // 当前访问的页码,最低为1
$maxpage = max(ceil($total / $size), 1); // 计算总页数,最低为1
if ($maxpage == 1) {
return ''; //判断$maxpage是否为1,如果总数只有一页,则直接返回空字符串
}
$html = ["<ul class=\"pagination\">"];
// 用来生成分页导航中每个链接
if ($page > 1) { // 判断当前是否在第一页
$html[] = "<li><a href=\"{$url}1\">首页</a></li>"; //显示禁用的首页
$html[] = '<li><a href="' . $url . ($page - 1) . '">上一页</a></li>'; //显示禁用的下一页
} else {
$html[] = '<li class="disabled"><span>首页</span></li>'; //显示首页
$html[] = '<li class="disabled"><span>上一页</span></li>'; //显示上一页
}
$num = floor($num / 2); // 计算当前页前后页码链接个数
$start = $page - $num; // 计算最左边显示的页码
$end = $page + $num; // 计算最右边显示的页码
if ($start < 1) {
$end = $end + (1 - $start);
$start = 1;
}
if ($end > $maxpage) {
$start = $start - ($end - $maxpage);
if ($start < 1) {
$start = 1;
}
$end = $maxpage;
}
if ($start > 1) {
$html[] = '<li class="disabled"><span>。。。</span></li>';
}
for ($i = $start; $i <= $end; $i++) {
if ($i == $page) {
$html[] = "<li class=\"active\"><span>$i</span></li>";
} else {
$html[] = "<li ><a href=\"{$url}{$i}\">$i</a></li>";
}
}
if ($end < $maxpage) {
$html[] = '<li class="disable"><span>。。。</span></li>';
}
if ($page == $maxpage) {
$html[] = '<li class="disabled"><span>下一页</span></li>';
$html[] = '<li class="disabled"><span>尾页</span></li>';
} else {
$html[] = '<li><a href="' . $url. ($page + 1) . '">下一页</a></li>';
$html[] = "<li><a href=\"{$url}{$maxpage}\">尾页</a></li>";
}
$html[] = '</ul>';
return implode('', $html);
}
}
3.在视图中输出
<div class="text-center">{$page_html nofilter}</div>
4.在模型里添加一个获取总数记录的方法
public function count() //获取文章总数记录
{
$table = $this->table;
$where = $this->options['where'];
$sql = "SELECT COUNT(*) AS c FROM $table $where";
$res = $this->db->fetchRow($sql, $this->options['data']);
$this->resetOption();
return $res ? $res['c'] : null;
}
上述代码仅供参考,如果有该兴趣的同学可以联系作者:qq3067339721