运行截图如下:
前端代码如下:
Student.php
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>HelloWorld</h1> <table border="1" cellspacing="1" cellpadding="1"> <thead> <tr> <td>ID</td> <td>名字</td> <td>年龄</td> <td>性别</td> <td>邮箱</td> <td>地址</td> <td>更新时间</td> </tr> </thead> <tbody> {foreach $students as $student} <tr> <td>{$student.id}</td> <td>{$student.name}</td> <td>{$student.age}</td> <td> {if $student.sex eq "m"} 男 {else}女 {/if} </td> <td>{$student.email}</td> <td>{$student.address}</td> <td>{$student.updateTime}</td> </tr> {/foreach} </tbody> </table> <ul> {$pageStr} </ul> </body> </html>
后端关键代码
提供数据的:
StudentController.php
<?php namespace admin\controller; use core\Controller; use home\model\StudentModel; use vendor\Page; class StudentController extends Controller{ public function student(){ $page = $_REQUEST["page"] ?? 1; $studentModel = new StudentModel(); $students = $studentModel->getAllStudents($page); $counts = $studentModel->getCounts(); $cond = array("a" => A, "c" => C, "p" => P); $pageStr = Page::clickPage(URL . "index.php", $counts, $cond, $page); $this->assign("pageStr", $pageStr); $this->assign("students", $students); $this->assign("counts", $counts); $this->display("student.html"); } }
分页代码:
Page.php
<?php namespace vendor; class Page{ public static function clickPage($url, $counts, $cond = array(), $page = 1, $pageCount = 5): string{ //所有页数 $pages = ceil($counts / $pageCount); //上一页和下一页 $prev = $page > 1 ? $page - 1 : 1; $next = $page < $pages ? $page + 1 : $pages; //url上需要补充的内容 $patchInfo = ""; foreach ($cond as $key => $value){ $patchInfo .= $key . "=" . $value . "&"; } //先展示上一页 $click = "<li><a href='{$url}?{$patchInfo}page={$prev}'>上一页</a></li>"; //如果总页数在7以内全都都展示出来 if($pages <= 7){ for($i = 1; $i <= $pages; $i++){ $click .= "<li><a href='{$url}?{$patchInfo}page={$i}'>{$i}</a></li>"; } } else{ //总页数在7页以上 //如果当前选中页数在5页以内,就把前7页全显示了。 if($page <= 5){ for($i = 1; $i <= 7; $i++){ $click .= "<li><a href='{$url}?{$patchInfo}page={$i}'>{$i}</a></li>"; } $click .= "<li><a href='#'>...</a></li>"; } else{ //如果当前选中的在第7页(包括第7页)以上,先展示1,2 $click .= "<li><a href='{$url}?{$patchInfo}page=1'>1</a></li>"; $click .= "<li><a href='{$url}?{$patchInfo}page=2'>2</a></li>"; $click .= "<li><a href='#'>...</a></li>"; //再展示中间页 //如果是最后3页了,就全部展示出来 if($pages - $page <= 3){ for($i = $pages - 4; $i <= $pages; $i++){ $click .= "<li><a href='{$url}?{$patchInfo}page={$i}'>{$i}</a></li>"; } } else{ //展示当前页面的前2页,和后2页 for($i = $page - 2; $i <= $page + 2; $i++){ $click .= "<li><a href='{$url}?{$patchInfo}page={$i}'>{$i}</a></li>"; } $click .= "<li><a href='#'>...</a></li>"; } } } //最后补一个下一页 $click .= "<li><a href='{$url}?{$patchInfo}page={$next}'>下一页</a></li>"; return $click; } }
简单说下逻辑:
http://localhost:63343/IT1995Blog/public/index.php?a=student&c=Student&p=admin&page=2
这个page就是当前页,程序里面写死了是每页5条,a=student,c=Student,p=admin是程序里面的逻辑,这个是必须要加的。所以在Page中会补这个。