Correction status:qualified
Teacher's comments:
PHP+SQLi 超级简单分页函数实例 不废话看源码
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>超级简单的分页函数</title> <style> table,th,td { border: 1px solid black; } table th { background-color: lightskyblue; } table { border-collapse: collapse; width: 70%; margin: 30px auto; text-align: center; } h3 { text-align: center; } h3 a { text-decoration: none; margin-left: 10px; display: inline-block; height: 30px; min-width: 30px; padding: 0 10px; background-color: #e3e3e3; } h3 a:hover, .active { background-color: #000; color: white; } form { display: inline; } </style> </head> <body> <?php require 'fun_page.php'; $db=mysqli_connect('127.0.0.1','root','root','test'); $page=isset($_GET['p']) ? $_GET['p'] : 1; $num=5; $table='yuangong'; $data = fun_page($db,$table,$page,$num); $rows=$data['rows']; $pages=$data['pages']; $page=($page==0) ? 1 :$page; $page=($page > $pages) ? $page : $page; ?> <table> <caption><h2>员工信息表</h2></caption> <tr> <td>ID</td> <td>姓名</td> <td>电话</td> <td>年龄</td> </tr> <?php foreach($rows as $row): ?> <tr> <td><?php echo $row['userID']; ?></td> <td><?php echo $row['userName']; ?></td> <td><?php echo $row['phone']; ?></td> <td><?php echo $row['age']; ?></td> </tr> <?php endforeach; ?> </table> <h3> <!-- 当前是第一页的时候,上一页和首页链接应该不显示--> <?php if($page != 1): ?> <a href="http://xumq.cn/php/0427/page.php?p=1">首页</a> <a href="http://xumq.cn/php/0427/page.php?p=<?php echo $page-1; ?>">上一页</a> <?php endif; ?> <form action=""method="post"> 第 <select name="p" id="p"> <?php for($i=1; $i<=$pages; $i++): ?> <option value="<?php echo $i ;?>" <?php if($_GET['p']==$i){echo 'selected';} ?>><?php echo $i;?> </option> <?php endfor; ?> </select> </form> <!--当前已经是最后一页的时候,下一页和最后一页也应该不显示--> <?php if($page != $pages) :?> <a href="http://xumq.cn/php/0427/page.php?p=<?php echo $page+1; ?>">下一页</a> <a href="http://xumq.cn/php/0427/page.php?p=<?php echo $pages; ?>">尾页</a> <?php endif; ?> </h3> </table> </body> </html>
分页函数页面源码fun_page.php
if(!function_exists('fun_page')){ /* * 分页函数 * $db 数据库 * $table 表名 * $page 当前页 默认第一页 * $num 每页显示的记录数 默认5条 */ function fun_page($db,$table,$page=1,$num=5){ $offset=($page-1)*$num; $sql="SELECT * FROM {$table} LIMIT {$offset},{$num};"; $res=mysqli_query($db,$sql); $rows=mysqli_fetch_all($res,MYSQLI_ASSOC); //获取分页:1。获取总记录数,2。再除以每次的显示数量,结果向上取整 $number =mysqli_query($db,"SELECT COUNT(*) FROM {$table}"); list($total)=mysqli_fetch_row($number); $pages=ceil($total/$num); //返回总记录数和总页数 return ['rows'=>$rows,'pages'=>$pages]; } }