php分页代码实现
基本分页实现
使用LIMIT和OFFSET进行数据库查询分页
$perPage = 10; // 每页显示数量
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1; // 当前页码
$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);
$totalRow = $totalResult->fetch_assoc();
$total = $totalRow['total'];
// 计算总页数
$totalPages = ceil($total / $perPage);
分页链接生成
创建分页导航HTML
$url = $_SERVER['PHP_SELF'] . '?'; // 当前页面URL
$query = $_GET;
unset($query['page']); // 移除原有page参数
if (!empty($query)) {
$url .= http_build_query($query) . '&';
}
// 生成分页链接
echo '<div class="pagination">';
if ($page > 1) {
echo '<a href="' . $url . 'page=' . ($page - 1) . '">上一页</a>';
}
for ($i = 1; $i <= $totalPages; $i++) {
if ($i == $page) {
echo '<span class="current">' . $i . '</span>';
} else {
echo '<a href="' . $url . 'page=' . $i . '">' . $i . '</a>';
}
}
if ($page < $totalPages) {
echo '<a href="' . $url . 'page=' . ($page + 1) . '">下一页</a>';
}
echo '</div>';
优化分页查询
使用预处理语句防止SQL注入
$stmt = $conn->prepare("SELECT * FROM your_table LIMIT ?, ?");
$stmt->bind_param("ii", $offset, $perPage);
$stmt->execute();
$result = $stmt->get_result();
大数据量分页优化
使用"上一页/下一页"模式替代传统分页
$nextPage = $page + 1;
$prevPage = $page - 1;
echo '<div class="pagination">';
if ($prevPage > 0) {
echo '<a href="' . $url . 'page=' . $prevPage . '">上一页</a>';
}
if ($nextPage <= $totalPages) {
echo '<a href="' . $url . 'page=' . $nextPage . '">下一页</a>';
}
echo '</div>';
使用分页类
封装分页逻辑为可重用类
class Pagination {
private $total;
private $perPage;
private $currentPage;
private $url;
public function __construct($total, $perPage, $currentPage, $url) {
$this->total = $total;
$this->perPage = $perPage;
$this->currentPage = $currentPage;
$this->url = $url;
}
public function getLinks() {
$totalPages = ceil($this->total / $this->perPage);
$html = '<div class="pagination">';
if ($this->currentPage > 1) {
$html .= '<a href="' . $this->url . ($this->currentPage - 1) . '">上一页</a>';
}
for ($i = 1; $i <= $totalPages; $i++) {
if ($i == $this->currentPage) {
$html .= '<span class="current">' . $i . '</span>';
} else {
$html .= '<a href="' . $this->url . $i . '">' . $i . '</a>';
}
}
if ($this->currentPage < $totalPages) {
$html .= '<a href="' . $this->url . ($this->currentPage + 1) . '">下一页</a>';
}
$html .= '</div>';
return $html;
}
}






