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;
<?php
//页码来自GET参数
$page = $_GET['page'] ?? 1;
//三元越界检查
$page = $page < 1 ? 1 : $page;
//每页显示数量
$num = 5;
//获取分页数据
$db = new PDO('mysql:host=localhost;dbname=phpedu', 'root', 'root');
$sql = 'select * from users limit ?,?';
$stmt = $db->prepare($sql);
$stmt->bindParam(1, $offset, PDO::PARAM_INT);
$stmt->bindParam(2, $num, PDO::PARAM_INT);
//计算偏移量
$offset = ($page - 1) * $num;
$stmt->execute();
// $stmt->debugDumpParams();
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);
// print_r($users);
//计算总页数
// 1.计算总数量
$sql = "SELECT count(id) as total FROM users";
$stmt = $db->prepare($sql);
$stmt->execute();
//将字段 total 绑定到一个变量上
$stmt->bindColumn('total', $total);
$stmt->fetch();
// echo $total;
// 2.计算总页数
$pages = ceil($total / $num);
echo $page;
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<table border="1" width='300'>
<caption>用户表</caption>
<thead>
<tr>
<th>用户ID</th>
<th>用户名</th>
<th>邮箱</th>
<th>性别</th>
</tr>
</thead>
<tbody>
<?php foreach ($users as $user) : ?>
<tr>
<td><?= $user['id']; ?></td>
<td><?= $user['uname']; ?></td>
<td><?= $user['email']; ?></td>
<td><?= $user['sex'] ? '男' : '女'; ?></td>
</tr>
<?php endforeach ?>
</tbody>
</table>
<p>
<?php $style = 'style="background:red"'; ?>
<a href="?page=<?= $page - 1 ?>">上一页</a>
<?php for ($i = 1; $i <= $pages; $i++) : ?>
<?php $active = ($i == $_GET['page']) ? $style : null; ?>
<a href=" ?page=<?= $i ?>" <?= $active ?>><?= $i; ?></a>
<?php endfor ?>
<a href="?page=<?= ($page != $pages) ? ($page + 1) : $page ?>">下一页</a>
</p>
</body>
</html>