PHP实现下页
PHP实现分页功能
分页功能是Web开发中常见的需求,用于将大量数据分割成多个页面显示。以下是PHP实现分页的几种方法:
基础分页实现
使用MySQL的LIMIT语句结合PHP实现基础分页:
$perPage = 10; // 每页显示记录数
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$start = ($page - 1) * $perPage;
$sql = "SELECT * FROM table_name LIMIT $start, $perPage";
$result = mysqli_query($conn, $sql);
计算总页数
获取总记录数并计算总页数:
$totalQuery = "SELECT COUNT(*) as total FROM table_name";
$totalResult = mysqli_query($conn, $totalQuery);
$totalRow = mysqli_fetch_assoc($totalResult);
$totalPages = ceil($totalRow['total'] / $perPage);
生成分页链接
创建分页导航链接:
for ($i = 1; $i <= $totalPages; $i++) {
echo "<a href='?page=$i'>$i</a> ";
}
使用PDO实现分页
PDO方式更安全,可防止SQL注入:
$db = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$stmt = $db->prepare("SELECT * FROM table_name LIMIT :start, :perPage");
$stmt->bindValue(':start', $start, PDO::PARAM_INT);
$stmt->bindValue(':perPage', $perPage, PDO::PARAM_INT);
$stmt->execute();
分页类封装
创建可重用的分页类:
class Pagination {
private $perPage;
private $page;
private $total;
public function __construct($perPage, $total) {
$this->perPage = $perPage;
$this->page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$this->total = $total;
}
public function getOffset() {
return ($this->page - 1) * $this->perPage;
}
public function getTotalPages() {
return ceil($this->total / $this->perPage);
}
public function getLinks() {
$links = '';
for ($i = 1; $i <= $this->getTotalPages(); $i++) {
$links .= "<a href='?page=$i'>$i</a> ";
}
return $links;
}
}
AJAX分页实现
实现无刷新分页效果:
// jQuery示例
$(document).on('click', '.pagination a', function(e) {
e.preventDefault();
var page = $(this).attr('href').split('page=')[1];
$.ajax({
url: 'get_data.php',
type: 'GET',
data: {page: page},
success: function(data) {
$('#content').html(data);
}
});
});
分页样式优化
使用Bootstrap美化分页导航:
echo '<nav aria-label="Page navigation"><ul class="pagination">';
for ($i = 1; $i <= $totalPages; $i++) {
$active = $i == $page ? 'active' : '';
echo "<li class='page-item $active'><a class='page-link' href='?page=$i'>$i</a></li>";
}
echo '</ul></nav>';
以上方法可根据实际项目需求进行组合和调整,实现适合项目的分页功能。







