博客列表 >实例演示简单分页操作

实例演示简单分页操作

晨
原创
2022年05月06日 09:30:07503浏览

分页数据准备代码showpages.php

  1. <?php
  2. namespace staff_table;
  3. use PDO;
  4. $db = new PDO('mysql:dbname=phpedu', 'root', 'root');
  5. $page = $_GET['p'] ?? 1;
  6. echo "当前页: p= $page <br>";
  7. $num = 10;
  8. $sql = 'SELECT COUNT(`id`) AS `total` FROM `staff`';
  9. $stmt = $db->prepare($sql);
  10. $stmt->execute();
  11. $stmt->bindColumn('total',$total);
  12. $stmt->fetch(PDO::FETCH_ASSOC);
  13. echo "总记录数量:$total <br>";
  14. $pages = ceil($total / $num);
  15. echo "总页数: $pages <br>";
  16. $offset = ($page - 1) * $num;
  17. echo "偏移量:$offset <br>";
  18. $sql = "SELECT * FROM `staff` LIMIT $offset,$num";
  19. $stmt = $db->prepare($sql);
  20. $stmt->execute();
  21. $staffs = $stmt->fetchAll(PDO::FETCH_ASSOC);

页面展示分页数据presentation.php

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <?php
  4. require 'showpages.php'
  5. ?>
  6. <head>
  7. <meta charset="UTF-8">
  8. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  9. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  10. <title>页面展示分页数据</title>
  11. <style>
  12. table {
  13. width: 400px;
  14. border-collapse: collapse;
  15. text-align: center;
  16. }
  17. table th,
  18. table td {
  19. border: 1px solid;
  20. padding: 5px;
  21. }
  22. table thead {
  23. background-color: lightcyan;
  24. }
  25. table caption {
  26. font-size: larger;
  27. margin-bottom: 8px;
  28. }
  29. p>a {
  30. text-decoration: none;
  31. color: #555;
  32. border: 1px solid;
  33. padding: 5px 10px;
  34. margin: 10px 2px;
  35. }
  36. .active {
  37. background-color: seagreen;
  38. color: white;
  39. border: 1px solid seagreen;
  40. }
  41. </style>
  42. </head>
  43. <body>
  44. <table>
  45. <caption>员工信息表</caption>
  46. <thead>
  47. <tr>
  48. <td>ID</td>
  49. <td>姓名</td>
  50. <td>性别</td>
  51. <td>邮箱</td>
  52. </tr>
  53. </thead>
  54. <tbody>
  55. <?php foreach ($staffs as $staff) : extract($staff) ?>
  56. <tr>
  57. <td><?=$id ?></td>
  58. <td><?=$name ?></td>
  59. <td><?=($sex ? '女' : '男')?></td>
  60. <td><?=$email ?>></td>
  61. </tr>
  62. <?php endforeach ?>
  63. </tbody>
  64. </table>
  65. <p>
  66. <?php for ($i = 1 ; $i <= $pages; $i++) : ?>
  67. <?php
  68. $url = $_SERVER['PHP_SELF'] . '?p=' . $i;
  69. $active = $i == $_GET['p'] ? 'active' : null;
  70. ?>
  71. <a href="<?= $url ?>" class="<?= $active ?>"><?= $i ?></a>
  72. <?php endfor ?>
  73. </p>
  74. </body>
  75. </html>
声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议