Blogger Information
Blog 94
fans 0
comment 0
visits 92750
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
【PHP】PHP分页
可乐随笔
Original
541 people have browsed it

PHP分页

1.页码来源:$_GET['page']
2.三元越界检查:$page<1,赋值:1
3.定义每页显示数量:$num
4.获取数据量:$users
5.计算总页数:$pages = ceil($user/$num)
6.获取偏移量:offset=($page-1)*$num
7.获取分页数据:select * from users limit $offset,$num;

  1. <?php
  2. //页码来自GET参数
  3. $page = $_GET['page'] ?? 1;
  4. //三元越界检查
  5. $page = $page < 1 ? 1 : $page;
  6. //每页显示数量
  7. $num = 5;
  8. //获取分页数据
  9. $db = new PDO('mysql:host=localhost;dbname=phpedu', 'root', 'root');
  10. $sql = 'select * from users limit ?,?';
  11. $stmt = $db->prepare($sql);
  12. $stmt->bindParam(1, $offset, PDO::PARAM_INT);
  13. $stmt->bindParam(2, $num, PDO::PARAM_INT);
  14. //计算偏移量
  15. $offset = ($page - 1) * $num;
  16. $stmt->execute();
  17. // $stmt->debugDumpParams();
  18. $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
  19. // print_r($users);
  20. //计算总页数
  21. // 1.计算总数量
  22. $sql = "SELECT count(id) as total FROM users";
  23. $stmt = $db->prepare($sql);
  24. $stmt->execute();
  25. //将字段 total 绑定到一个变量上
  26. $stmt->bindColumn('total', $total);
  27. $stmt->fetch();
  28. // echo $total;
  29. // 2.计算总页数
  30. $pages = ceil($total / $num);
  31. echo $page;
  32. ?>
  33. <!DOCTYPE html>
  34. <html lang="en">
  35. <head>
  36. <meta charset="UTF-8">
  37. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  38. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  39. <title>Document</title>
  40. </head>
  41. <body>
  42. <table border="1" width='300'>
  43. <caption>用户表</caption>
  44. <thead>
  45. <tr>
  46. <th>用户ID</th>
  47. <th>用户名</th>
  48. <th>邮箱</th>
  49. <th>性别</th>
  50. </tr>
  51. </thead>
  52. <tbody>
  53. <?php foreach ($users as $user) : ?>
  54. <tr>
  55. <td><?= $user['id']; ?></td>
  56. <td><?= $user['uname']; ?></td>
  57. <td><?= $user['email']; ?></td>
  58. <td><?= $user['sex'] ? '男' : '女'; ?></td>
  59. </tr>
  60. <?php endforeach ?>
  61. </tbody>
  62. </table>
  63. <p>
  64. <?php $style = 'style="background:red"'; ?>
  65. <a href="?page=<?= $page - 1 ?>">上一页</a>
  66. <?php for ($i = 1; $i <= $pages; $i++) : ?>
  67. <?php $active = ($i == $_GET['page']) ? $style : null; ?>
  68. <a href=" ?page=<?= $i ?>" <?= $active ?>><?= $i; ?></a>
  69. <?php endfor ?>
  70. <a href="?page=<?= ($page != $pages) ? ($page + 1) : $page ?>">下一页</a>
  71. </p>
  72. </body>
  73. </html>
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post