php分页功能的实现
基本分页实现
使用 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);
$totalRow = $totalResult->fetch_assoc();
$totalPages = ceil($totalRow['total'] / $perPage);
分页链接生成
创建分页导航链接:
echo '<div class="pagination">';
for ($i = 1; $i <= $totalPages; $i++) {
$active = $i == $page ? 'active' : '';
echo "<a href='?page=$i' class='$active'>$i</a>";
}
echo '</div>';
使用预处理语句
为防止 SQL 注入,建议使用预处理语句:

$stmt = $conn->prepare("SELECT * FROM your_table LIMIT ?, ?");
$stmt->bind_param("ii", $offset, $perPage);
$stmt->execute();
$result = $stmt->get_result();
分页类封装
可以封装一个分页类方便复用:
class Pagination {
public $page;
public $perPage;
public $total;
public function __construct($total, $perPage = 10) {
$this->page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$this->perPage = $perPage;
$this->total = $total;
}
public function getOffset() {
return ($this->page - 1) * $this->perPage;
}
public function getTotalPages() {
return ceil($this->total / $this->perPage);
}
public function getLinks() {
$html = '<div class="pagination">';
for ($i = 1; $i <= $this->getTotalPages(); $i++) {
$active = $i == $this->page ? 'active' : '';
$html .= "<a href='?page=$i' class='$active'>$i</a>";
}
$html .= '</div>';
return $html;
}
}
前端样式建议
基本的分页样式 CSS:
.pagination {
display: flex;
gap: 5px;
margin-top: 20px;
}
.pagination a {
padding: 5px 10px;
border: 1px solid #ddd;
text-decoration: none;
}
.pagination a.active {
background: #007bff;
color: white;
border-color: #007bff;
}






