php分页实现
基础分页实现
使用MySQL的LIMIT和OFFSET实现分页。获取当前页码$page和每页显示数量$perPage:
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$perPage = 10;
$offset = ($page - 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);
生成分页链接
创建简单的分页导航链接:
echo '<div class="pagination">';
for ($i = 1; $i <= $totalPages; $i++) {
echo '<a href="?page='.$i.'">'.$i.'</a>';
}
echo '</div>';
使用预处理语句防止SQL注入
改进SQL查询安全性:

$stmt = $conn->prepare("SELECT * FROM articles LIMIT ?, ?");
$stmt->bind_param("ii", $offset, $perPage);
$stmt->execute();
$result = $stmt->get_result();
分页样式优化
添加CSS样式美化分页导航:
.pagination a {
display: inline-block;
padding: 8px 16px;
text-decoration: none;
border: 1px solid #ddd;
margin: 0 4px;
}
.pagination a.active {
background-color: #4CAF50;
color: white;
border: 1px solid #4CAF50;
}
高级分页功能
实现带省略号的分页导航:
function pagination($currentPage, $totalPages) {
$range = 2;
$html = '<div class="pagination">';
if ($currentPage > 1) {
$html .= '<a href="?page=1">«</a>';
$html .= '<a href="?page='.($currentPage-1).'">‹</a>';
}
for ($i = max(1, $currentPage - $range); $i <= min($currentPage + $range, $totalPages); $i++) {
$active = $i == $currentPage ? ' class="active"' : '';
$html .= '<a'.$active.' href="?page='.$i.'">'.$i.'</a>';
}
if ($currentPage < $totalPages) {
$html .= '<a href="?page='.($currentPage+1).'">›</a>';
$html .= '<a href="?page='.$totalPages.'">»</a>';
}
$html .= '</div>';
return $html;
}






