在PHP中實現(xiàn)數(shù)據(jù)分頁時,確保準確性的關(guān)鍵在于正確計算總頁數(shù)、當前頁碼以及每頁顯示的數(shù)據(jù)量。以下是一個簡單的示例,展示了如何使用PHP和MySQL實現(xiàn)數(shù)據(jù)分頁:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("連接失敗: " . $conn->connect_error);
}
$perPage = 10; // 每頁顯示的數(shù)據(jù)量
$page = isset($_GET['page']) ? intval($_GET['page']) : 1; // 當前頁碼,默認為第一頁
// 計算偏移量
$offset = ($page - 1) * $perPage;
// 查詢數(shù)據(jù)
$sql = "SELECT * FROM myTable LIMIT $offset, $perPage";
$result = $conn->query($sql);
$data = [];
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
} else {
echo "0 結(jié)果";
}
$sqlTotal = "SELECT COUNT(*) as total FROM myTable";
$resultTotal = $conn->query($sqlTotal);
$totalRow = $resultTotal->fetch_assoc();
$total = $totalRow['total'];
$totalPages = ceil($total / $perPage); // 計算總頁數(shù)
for ($i = 1; $i <= $totalPages; $i++) {
echo "<a href='?page=$i'>$i</a> ";
}
$conn->close();
通過以上步驟,你可以實現(xiàn)一個簡單的PHP數(shù)據(jù)分頁。請注意,為了避免SQL注入攻擊,建議使用預(yù)處理語句(prepared statements)來執(zhí)行查詢。在實際項目中,你可能還需要考慮其他因素,例如用戶體驗、錯誤處理和安全性等。