php实现分页步骤
连接数据库并获取数据
使用PDO或MySQLi连接数据库,执行SQL查询获取总数据量。例如:
$pdo = new PDO("mysql:host=localhost;dbname=test", "username", "password");
$totalQuery = $pdo->query("SELECT COUNT(*) FROM products");
$totalItems = $totalQuery->fetchColumn();
计算分页参数
确定当前页码、每页显示数量及总页数:
$itemsPerPage = 10;
$currentPage = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$totalPages = ceil($totalItems / $itemsPerPage);
$offset = ($currentPage - 1) * $itemsPerPage;
查询当前页数据
使用LIMIT子句获取当前页数据:

$stmt = $pdo->prepare("SELECT * FROM products LIMIT :offset, :limit");
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt->bindValue(':limit', $itemsPerPage, PDO::PARAM_INT);
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
生成分页导航
创建可点击的分页链接:
$pagination = '';
for ($i = 1; $i <= $totalPages; $i++) {
$active = ($i == $currentPage) ? ' class="active"' : '';
$pagination .= "<a href=\"?page=$i\"$active>$i</a> ";
}
显示数据和分页控件
将查询结果和分页导航输出到页面:

foreach ($results as $row) {
echo "<div>{$row['product_name']}</div>";
}
echo "<div class='pagination'>$pagination</div>";
样式优化(可选)
添加CSS美化分页导航:
.pagination a {
padding: 5px 10px;
margin: 0 2px;
border: 1px solid #ddd;
}
.pagination a.active {
background-color: #007bff;
color: white;
}
安全注意事项
对用户输入的页码进行过滤:
$currentPage = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT, [
'options' => ['default' => 1, 'min_range' => 1]
]);





