分页查询的原理与偏移量的计算方法?
根据数据库,设定每页显示数量,获取偏移量,接收GET参数,用p表示当前页数,需要的参数:totalPage 总页数,totalNumber 一共有多少条数据,pageSize 每页显示多少条数据,currentPage 当前第几页,rangeStart 起始页,rangeEnd 末页。当前偏移量的计算公式: (页数-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(); $result=$stmt->fetchAll(PDO::FETCH_ASSOC); $stmt=$pdo->prepare("select COUNT(*) from staff"); $stmt->execute(); $total=$stmt->fetchColumn(); $pages=ceil($total/5); ?> <!doctype html> <html> <head> <meta charset="UTF-8"> <title>Document</title> <style> table ,td{ border: 1px solid black; } table{ border-collapse: collapse; width: 60%; margin: 30px auto; text-align: center; } tr:first-child{ background-color: lightblue; } table caption{ font-size: 20px; margin-bottom: 15px; } h3{ text-align: center; } h3 a{ text-decoration: none; display: inline-block; border: 1px solid black; height: 30px; min-width: 30px; padding: 0 10px; background-color: lightblue; margin-left: 10px; } h3 a:hover{ background-color: red; color: white; } form { display: inline; } </style> </head> <body> <table> <caption>员工信息表</caption> <tr> <td>ID</td> <td>姓名</td> <td>年龄</td> <td>性别</td> <td>工资</td> </tr> <?php foreach ($result as $staff):?> <tr> <td><?php echo $staff['staff_id'];?></td> <td><?php echo $staff['name'];?></td> <td><?php echo $staff['age'];?></td> <td><?php echo $staff['sex']?'女':'男';?></td> <td><?php echo $staff['salary'];?></td> </tr> <?php endforeach;?> </table> <h3> <a href="http://127.0.0.1/page/demo1.php?p=1">首页</a> <a href="http://127.0.0.1/page/demo1.php?p=<?php echo (($page-1)==0)?1:($page-1);?>">上一页</a> <?php for ($i=1;$i<=$pages;$i++):?> <a href="http://127.0.0.1/page/demo1.php?p=<?php echo $i?>"<?php echo ($i==$page)?'style="background-color:red;"':''?>><?php echo $i?></a> <?php endfor;?> <a href="http://127.0.0.1/page/demo1.php?p=<?php echo (($page+1)>$pages)?$pages:($page+1);?>">下一页</a> <a href="http://127.0.0.1/page/demo1.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>
运行实例 »
点击 "运行实例" 按钮查看在线实例