用php实现分页
使用 PHP 实现分页
数据库查询与分页逻辑
分页的核心是通过 SQL 的 LIMIT 子句限制返回的数据量。假设从名为 articles 的表中分页查询数据:
<?php
// 连接数据库
$db = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
// 当前页码,默认为第1页
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$perPage = 10; // 每页显示10条数据
$offset = ($page - 1) * $perPage; // 计算偏移量
// 查询总记录数
$totalStmt = $db->query("SELECT COUNT(*) FROM articles");
$total = $totalStmt->fetchColumn();
// 查询当前页数据
$stmt = $db->prepare("SELECT * FROM articles LIMIT :offset, :perPage");
$stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
$stmt->bindParam(':perPage', $perPage, PDO::PARAM_INT);
$stmt->execute();
$articles = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
生成分页链接
根据总记录数和每页显示数量计算总页数,并生成分页导航:
<?php
$totalPages = ceil($total / $perPage); // 计算总页数
// 生成分页链接
echo '<div class="pagination">';
if ($page > 1) {
echo '<a href="?page=' . ($page - 1) . '">上一页</a>';
}
for ($i = 1; $i <= $totalPages; $i++) {
$active = $i == $page ? ' class="active"' : '';
echo '<a href="?page=' . $i . '"' . $active . '>' . $i . '</a>';
}
if ($page < $totalPages) {
echo '<a href="?page=' . ($page + 1) . '">下一页</a>';
}
echo '</div>';
?>
样式优化(可选)
为分页导航添加基础 CSS 样式:
.pagination {
margin: 20px 0;
display: flex;
gap: 5px;
}
.pagination a {
padding: 5px 10px;
border: 1px solid #ddd;
text-decoration: none;
}
.pagination a.active {
background: #007bff;
color: white;
}
完整示例
将数据库查询、分页逻辑和界面展示整合:
<?php
// 连接数据库
$db = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
// 分页参数
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$perPage = 10;
$offset = ($page - 1) * $perPage;
// 获取总记录数
$totalStmt = $db->query("SELECT COUNT(*) FROM articles");
$total = $totalStmt->fetchColumn();
$totalPages = ceil($total / $perPage);
// 获取当前页数据
$stmt = $db->prepare("SELECT * FROM articles LIMIT :offset, :perPage");
$stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
$stmt->bindParam(':perPage', $perPage, PDO::PARAM_INT);
$stmt->execute();
$articles = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!-- 显示数据 -->
<ul>
<?php foreach ($articles as $article): ?>
<li><?= htmlspecialchars($article['title']) ?></li>
<?php endforeach; ?>
</ul>
<!-- 分页导航 -->
<div class="pagination">
<?php if ($page > 1): ?>
<a href="?page=<?= $page - 1 ?>">上一页</a>
<?php endif; ?>
<?php for ($i = 1; $i <= $totalPages; $i++): ?>
<a href="?page=<?= $i ?>" <?= $i == $page ? 'class="active"' : '' ?>>
<?= $i ?>
</a>
<?php endfor; ?>
<?php if ($page < $totalPages): ?>
<a href="?page=<?= $page + 1 ?>">下一页</a>
<?php endif; ?>
</div>
注意事项
- 安全性:始终对用户输入的页码进行类型转换和验证,防止 SQL 注入。
- 性能:大数据表分页时,避免使用
COUNT(*),可通过缓存或估算优化。 - 扩展性:复杂场景可封装独立的分页类,支持自定义样式和参数。







