要避免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數據分頁中的錯誤發生。