要通过MySQL的ROW()函数实现数据的分页显示,你可以使用以下方法:
SELECT COUNT(*) FROM your_table;
SELECT CEIL(total_records / records_per_page) as total_pages FROM (
SELECT COUNT(*) as total_records FROM your_table
) as subquery;
-- 获取第2页的数据,每页显示10条记录
SELECT * FROM your_table
ORDER BY id
LIMIT 10 OFFSET 10;
<?php
$host = 'localhost';
$username = 'your_username';
$password = 'your_password';
$dbname = 'your_database';
// 创建连接
$conn = new mysqli($host, $username, $password, $dbname);
// 检查连接
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
// 每页显示的记录数
$records_per_page = 10;
// 获取请求的页码
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
// 计算偏移量
$offset = ($page - 1) * $records_per_page;
// 查询总记录数
$sql_total_records = "SELECT COUNT(*) as total_records FROM your_table";
$result_total_records = $conn->query($sql_total_records);
$total_records = $result_total_records->fetch_assoc()['total_records'];
// 计算总页数
$total_pages = ceil($total_records / $records_per_page);
// 获取当前页的数据
$sql_data = "SELECT * FROM your_table ORDER BY id LIMIT $records_per_page OFFSET $offset";
$result_data = $conn->query($sql_data);
// 显示数据
if ($result_data->num_rows > 0) {
while($row = $result_data->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 结果";
}
// 显示分页导航
for ($i = 1; $i <= $total_pages; $i++) {
echo "<a href='?page=$i'>$i</a> ";
}
// 关闭连接
$conn->close();
?>
这个示例中,我们首先获取请求的页码和每页显示的记录数。然后,我们计算偏移量并使用LIMIT和OFFSET关键字来获取当前页的数据。最后,我们显示数据和分页导航。