php分页代码简单实现
基本分页实现
使用PHP和MySQL实现分页功能,需要结合SQL的LIMIT子句。以下是一个基础示例:
<?php
// 数据库连接
$conn = new mysqli('localhost', 'username', 'password', 'database');
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// 获取当前页码
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$perPage = 10; // 每页显示条数
$start = ($page > 1) ? ($page - 1) * $perPage : 0;
// 查询数据总数
$total = $conn->query("SELECT COUNT(*) FROM table_name")->fetch_row()[0];
$pages = ceil($total / $perPage);
// 查询当前页数据
$result = $conn->query("SELECT * FROM table_name LIMIT $start, $perPage");
?>
<!-- 显示数据 -->
<?php while ($row = $result->fetch_assoc()): ?>
<div><?= $row['column_name'] ?></div>
<?php endwhile; ?>
<!-- 分页导航 -->
<div class="pagination">
<?php for ($i = 1; $i <= $pages; $i++): ?>
<a href="?page=<?= $i ?>" <?= ($i == $page) ? 'class="active"' : '' ?>>
<?= $i ?>
</a>
<?php endfor; ?>
</div>
使用预处理语句
为提高安全性,建议使用预处理语句:

$stmt = $conn->prepare("SELECT * FROM table_name LIMIT ?, ?");
$stmt->bind_param("ii", $start, $perPage);
$stmt->execute();
$result = $stmt->get_result();
分页样式优化
添加简单的CSS样式美化分页导航:

.pagination {
margin-top: 20px;
}
.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;
}
.pagination a:hover:not(.active) {
background-color: #ddd;
}
分页函数封装
将分页逻辑封装成可重用函数:
function getPagination($conn, $table, $perPage = 10) {
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$start = ($page > 1) ? ($page - 1) * $perPage : 0;
$total = $conn->query("SELECT COUNT(*) FROM $table")->fetch_row()[0];
$pages = ceil($total / $perPage);
$result = $conn->query("SELECT * FROM $table LIMIT $start, $perPage");
return [
'data' => $result,
'page' => $page,
'pages' => $pages
];
}
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);
}
});
});






