php分页代码实现
基本分页实现
使用PHP和MySQL实现分页功能,需要计算总记录数、每页显示的记录数以及当前页码。
<?php
// 数据库连接
$conn = new mysqli('localhost', 'username', 'password', 'database');
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
// 每页显示记录数
$perPage = 10;
// 获取当前页码
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$start = ($page - 1) * $perPage;
// 查询总记录数
$totalQuery = "SELECT COUNT(*) as total FROM your_table";
$totalResult = $conn->query($totalQuery);
$totalRow = $totalResult->fetch_assoc();
$totalRecords = $totalRow['total'];
// 计算总页数
$totalPages = ceil($totalRecords / $perPage);
// 查询当前页数据
$query = "SELECT * FROM your_table LIMIT $start, $perPage";
$result = $conn->query($query);
?>
分页数据显示
循环显示查询到的数据:

<table>
<tr>
<th>ID</th>
<th>名称</th>
</tr>
<?php while($row = $result->fetch_assoc()): ?>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['name']; ?></td>
</tr>
<?php endwhile; ?>
</table>
分页导航生成
创建分页导航链接:
<div class="pagination">
<?php if($page > 1): ?>
<a href="?page=1">首页</a>
<a href="?page=<?php echo $page - 1; ?>">上一页</a>
<?php endif; ?>
<?php for($i = 1; $i <= $totalPages; $i++): ?>
<a href="?page=<?php echo $i; ?>" <?php if($i == $page) echo 'class="active"'; ?>><?php echo $i; ?></a>
<?php endfor; ?>
<?php if($page < $totalPages): ?>
<a href="?page=<?php echo $page + 1; ?>">下一页</a>
<a href="?page=<?php echo $totalPages; ?>">末页</a>
<?php endif; ?>
</div>
使用预处理语句的安全版本
为防止SQL注入,建议使用预处理语句:

<?php
// 使用预处理语句查询数据
$stmt = $conn->prepare("SELECT * FROM your_table 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 getPaginationData($conn, $table, $page = 1, $perPage = 10) {
$start = ($page - 1) * $perPage;
// 获取总记录数
$totalQuery = "SELECT COUNT(*) as total FROM $table";
$totalResult = $conn->query($totalQuery);
$totalRow = $totalResult->fetch_assoc();
$totalRecords = $totalRow['total'];
$totalPages = ceil($totalRecords / $perPage);
// 获取当前页数据
$query = "SELECT * FROM $table LIMIT $start, $perPage";
$result = $conn->query($query);
return [
'data' => $result,
'totalPages' => $totalPages,
'currentPage' => $page
];
}





