php分页效果实现
基本分页实现
使用 LIMIT 和 OFFSET 进行数据库查询分页。获取当前页码和每页显示数量,计算偏移量。
$currentPage = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$perPage = 10;
$offset = ($currentPage - 1) * $perPage;
$sql = "SELECT * FROM articles LIMIT $offset, $perPage";
$result = $conn->query($sql);
计算总页数
查询总记录数并计算总页数,用于生成分页导航。
$totalSql = "SELECT COUNT(*) as total FROM articles";
$totalResult = $conn->query($totalSql);
$totalRows = $totalResult->fetch_assoc()['total'];
$totalPages = ceil($totalRows / $perPage);
分页导航生成
创建分页链接,包含首页、上一页、页码和下一页、末页。
$baseUrl = 'http://example.com/articles.php?page=';
echo '<div class="pagination">';
if ($currentPage > 1) {
echo '<a href="' . $baseUrl . '1">首页</a>';
echo '<a href="' . $baseUrl . ($currentPage - 1) . '">上一页</a>';
}
for ($i = 1; $i <= $totalPages; $i++) {
$active = $i == $currentPage ? ' class="active"' : '';
echo '<a href="' . $baseUrl . $i . '"' . $active . '>' . $i . '</a>';
}
if ($currentPage < $totalPages) {
echo '<a href="' . $baseUrl . ($currentPage + 1) . '">下一页</a>';
echo '<a href="' . $baseUrl . $totalPages . '">末页</a>';
}
echo '</div>';
使用预处理语句
防止SQL注入,使用预处理语句处理分页参数。
$stmt = $conn->prepare("SELECT * FROM articles LIMIT ?, ?");
$stmt->bind_param("ii", $offset, $perPage);
$stmt->execute();
$result = $stmt->get_result();
分页样式优化
添加CSS样式美化分页导航,提高用户体验。
.pagination {
margin: 20px 0;
text-align: center;
}
.pagination a {
display: inline-block;
padding: 8px 16px;
margin: 0 4px;
border: 1px solid #ddd;
text-decoration: none;
color: #333;
}
.pagination a.active {
background-color: #4CAF50;
color: white;
border: 1px solid #4CAF50;
}
.pagination a:hover:not(.active) {
background-color: #ddd;
}
分页类封装
创建可重用的分页类,简化分页逻辑。
class Pagination {
private $currentPage;
private $perPage;
private $totalRows;
public function __construct($currentPage = 1, $perPage = 10, $totalRows = 0) {
$this->currentPage = $currentPage;
$this->perPage = $perPage;
$this->totalRows = $totalRows;
}
public function getOffset() {
return ($this->currentPage - 1) * $this->perPage;
}
public function getTotalPages() {
return ceil($this->totalRows / $this->perPage);
}
public function getPaginationLinks($baseUrl) {
$totalPages = $this->getTotalPages();
$links = '';
if ($this->currentPage > 1) {
$links .= '<a href="' . $baseUrl . '1">首页</a>';
$links .= '<a href="' . $baseUrl . ($this->currentPage - 1) . '">上一页</a>';
}
for ($i = 1; $i <= $totalPages; $i++) {
$active = $i == $this->currentPage ? ' class="active"' : '';
$links .= '<a href="' . $baseUrl . $i . '"' . $active . '>' . $i . '</a>';
}
if ($this->currentPage < $totalPages) {
$links .= '<a href="' . $baseUrl . ($this->currentPage + 1) . '">下一页</a>';
$links .= '<a href="' . $baseUrl . $totalPages . '">末页</a>';
}
return $links;
}
}






