php 实现分页
PHP 实现分页的方法
使用 LIMIT 和 OFFSET 进行数据库查询
在 MySQL 或其他 SQL 数据库中,可以使用 LIMIT 和 OFFSET 来实现分页查询。假设每页显示 10 条记录:
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$perPage = 10;
$offset = ($page - 1) * $perPage;
$sql = "SELECT * FROM your_table LIMIT $offset, $perPage";
$result = $conn->query($sql);
计算总页数
需要查询总记录数以计算总页数:
$totalSql = "SELECT COUNT(*) as total FROM your_table";
$totalResult = $conn->query($totalSql);
$totalRows = $totalResult->fetch_assoc()['total'];
$totalPages = ceil($totalRows / $perPage);
生成分页链接
在页面底部生成分页导航:
echo '<div class="pagination">';
for ($i = 1; $i <= $totalPages; $i++) {
echo "<a href='?page=$i'>$i</a> ";
}
echo '</div>';
使用 Bootstrap 美化分页
可以结合 Bootstrap 的分页组件:
echo '<nav aria-label="Page navigation">
<ul class="pagination">';
for ($i = 1; $i <= $totalPages; $i++) {
$active = ($i == $page) ? 'active' : '';
echo "<li class='page-item $active'><a class='page-link' href='?page=$i'>$i</a></li>";
}
echo '</ul></nav>';
预处理语句防止 SQL 注入
建议使用预处理语句:
$stmt = $conn->prepare("SELECT * FROM your_table LIMIT ?, ?");
$stmt->bind_param("ii", $offset, $perPage);
$stmt->execute();
$result = $stmt->get_result();
封装为可重用函数
可以将分页逻辑封装为函数:
function getPaginatedData($conn, $table, $page, $perPage) {
$offset = ($page - 1) * $perPage;
$stmt = $conn->prepare("SELECT * FROM $table LIMIT ?, ?");
$stmt->bind_param("ii", $offset, $perPage);
$stmt->execute();
return $stmt->get_result();
}
使用 PDO 实现
如果使用 PDO 连接数据库:
$pdo = new PDO("mysql:host=localhost;dbname=your_db", "username", "password");
$stmt = $pdo->prepare("SELECT * FROM your_table LIMIT :offset, :perPage");
$stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
$stmt->bindParam(':perPage', $perPage, PDO::PARAM_INT);
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
这些方法提供了从基础到进阶的 PHP 分页实现方式,可以根据项目需求选择适合的方案。







