php实现分页教程
PHP实现分页的基本步骤
使用PHP实现分页功能需要结合MySQL数据库查询和前端页面展示。以下是一个简单的分页实现方法。
获取总记录数并计算总页数:
$sql = "SELECT COUNT(*) FROM your_table";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_row($result);
$total_records = $row[0];
$total_pages = ceil($total_records / $per_page);
获取当前页码并计算LIMIT偏移量:

$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$start = ($page - 1) * $per_page;
查询当前页数据:
$sql = "SELECT * FROM your_table LIMIT $start, $per_page";
$result = mysqli_query($conn, $sql);
前端分页导航实现
在HTML中显示分页链接:

echo '<div class="pagination">';
for ($i = 1; $i <= $total_pages; $i++) {
echo "<a href='?page=$i'>$i</a> ";
}
echo '</div>';
使用预处理语句增强安全性
为了防止SQL注入,建议使用预处理语句:
$stmt = $conn->prepare("SELECT * FROM your_table LIMIT ?, ?");
$stmt->bind_param("ii", $start, $per_page);
$stmt->execute();
$result = $stmt->get_result();
分页样式优化
添加CSS样式美化分页导航:
.pagination a {
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;
}
完整分页类实现
创建一个可重用的分页类:
class Pagination {
private $total_records;
private $per_page;
public function __construct($total, $per_page) {
$this->total_records = $total;
$this->per_page = $per_page;
}
public function getTotalPages() {
return ceil($this->total_records / $this->per_page);
}
public function getOffset($page) {
return ($page - 1) * $this->per_page;
}
public function renderLinks($current_page, $url = '?page=') {
$html = '<div class="pagination">';
for ($i = 1; $i <= $this->getTotalPages(); $i++) {
$class = $i == $current_page ? 'active' : '';
$html .= "<a class='$class' href='{$url}{$i}'>{$i}</a> ";
}
$html .= '</div>';
return $html;
}
}






