要避免PHP數(shù)據(jù)分頁中的錯(cuò)誤,可以采取以下措施:
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) {
// 輸出數(shù)據(jù)
} else {
echo "沒有更多數(shù)據(jù)可以顯示";
}
$totalRows = $conn->query("SELECT COUNT(*) FROM table_name");
$totalPages = ceil($totalRows->fetch_row()[0] / $perPage);
if ($page > $totalPages) {
$page = $totalPages;
}
try {
// 數(shù)據(jù)分頁代碼
} catch (Exception $e) {
echo "發(fā)生錯(cuò)誤: " . $e->getMessage();
}
通過遵循這些步驟,可以有效地避免PHP數(shù)據(jù)分頁中的錯(cuò)誤發(fā)生。