博客列表 >分页基本操作

分页基本操作

P粉036614676
P粉036614676原创
2022年09月19日 09:14:09353浏览

1.分页文件

  1. <?php
  2. /**
  3. * $total :总信息条数
  4. *
  5. */
  6. $db = new PDO('mysql:host=localhost;dbname=test','root','901026yk');
  7. $sql = <<<SQL
  8. select count(*) as total from student;
  9. SQL;
  10. $stmt1 = $db->prepare($sql);
  11. $stmt1->execute();
  12. $stmt1->bindColumn(1,$total);
  13. $stmt1->fetch(PDO::FETCH_ASSOC);
  14. //获取总条数
  15. $page = $_GET['p'] ?? 1;
  16. $num = 2; //每页显示的数据条数
  17. $pages = ceil($total/$num);
  18. $offset = ($page - 1) * $num;
  19. $sql = <<<SQL
  20. select * from student limit $offset,$num;
  21. SQL;
  22. $stmt = $db->prepare($sql);
  23. $stmt->execute();
  24. $staff = $stmt->fetchAll(PDO::FETCH_ASSOC);

2.显示文件

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