要避免PHP数据分页中的错误,可以采取以下措施:
if (!is_numeric($page) || $page <= 0) {
$page = 1;
}
if (!is_numeric($perPage) || $perPage <= 0) {
$perPage = 10;
}
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
$stmt = $conn->prepare("SELECT * FROM table_name LIMIT ?, ?");
$stmt->bind_param("ii", $offset, $perPage);
$offset = ($page - 1) * $perPage;
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
// 输出数据
} else {
echo "没有更多数据可以显示";
}
$totalRows = $conn->query("SELECT COUNT(*) FROM table_name");
$totalPages = ceil($totalRows->fetch_row()[0] / $perPage);
if ($page > $totalPages) {
$page = $totalPages;
}
try {
// 数据分页代码
} catch (Exception $e) {
echo "发生错误: " . $e->getMessage();
}
通过遵循这些步骤,可以有效地避免PHP数据分页中的错误发生。