Correction status:qualified
Teacher's comments:
今天学习了分面查询原理与类封装的知识。
分页查询的原理与偏移量的计算方法
1. LIMIT 参数的作用: 偏移量与显示数量
2. 如果控制每页显示的数量
3. 接收GET参数,用p表示当前页数,每页显示3条
4. 需要的参数:
偏移量的计算方法
当前偏移量的计算公式: (页数-1)*每页显示的数量
* offset = (page-1)*num
代码
<?php $pdo=new PDO("mysql:host=127.0.0.1;dbname=php","root","root"); $page=isset($_GET['p'])?$_GET['p']:1; $offset=($page-1)*5; $sql="select * from staff limit {$offset},5"; $stmt=$pdo->prepare($sql); $stmt->execute(); $rows=$stmt->fetchAll(PDO::FETCH_ASSOC); //var_dump($rows); $stmt=$pdo->prepare("select count(*) from staff"); $stmt->execute(); $totals=$stmt->fetchColumn(0); $pages=ceil($totals/5); ?> <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>分页查询</title> <style> table,th,td{ border: 1px solid black; } table{ border-collapse: collapse; width: 60%; margin: 30px auto; text-align: center; } th{ background-color: aquamarine; margin-bottom: 15px; } caption{ font-size: 1.5rem; margin-bottom: 15px; } h3{ text-align: center; } h3 a{ text-decoration-line: none; display: inline-block; height: 30px; min-width: 30px; border: 1px solid black; background-color: aqua; color: black; padding: 0 10px; } a:hover{ background-color: red; color:white; } form{ display: inline; } </style> </head> <body> <table> <caption>员工信息表</caption> <tr> <th>staff_id</th> <th>name</th> <th>sex</th> <th>age</th> <th>salary</th> </tr> <?php foreach ($rows as $row):?> <tr> <td><?php echo $row['staff_id'];?></td> <td><?php echo $row['name'];?></td> <td><?php echo $row['sex']?'女':'男';?></td> <td><?php echo $row['age'];?></td> <td><?php echo $row['salary'];?></td> </tr> <?php endforeach;?> </table> <h3><a href="http://php.io/15/demo4.php?p=1">首页</a> <a href="http://php.io/15/demo4.php?p=<?php echo ($page-1==0)?1:($page-1) ;?>">上一页</a> <?php for($i=1;$i<$pages;$i++):?> <a href="http://php.io/15/demo4.php?p=<?php echo $i;?>" <?php echo ($i==$page)?"style=background-color:red":'';?>><?php echo $i;?></a> <?php endfor;?> <a href="http://php.io/15/demo4.php?p=<?php echo ($page+1>$pages)?$pages:($page+1);?>">下一页</a> <a href="http://php.io/15/demo4.php?p=<?php echo $pages;?>">尾页</a> <form action="" method="get"> <select name="p" id=""> <?php for($i=1;$i<$pages;$i++):;?> <option value="<?php echo $i;?>"<?php if($i==$page){ echo 'selected'; }?>><?php echo $i;?></option> <?php endfor;?> </select> <button>提交</button> </form> </h3> </body> </html>
点击 "运行实例" 按钮查看在线实例