在PHP中,實現分頁類時通常包含以下幾個步驟:
錯誤處理機制通常包括以下幾個方面:
mysqli_connect_error
異常。如果連接失敗,可以向用戶顯示錯誤信息并終止程序執行。$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("連接失敗: " . $conn->connect_error);
}
PDOException
異常。如果查詢失敗,可以向用戶顯示錯誤信息并終止程序執行。$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT id, name FROM myTable";
$stmt = $conn->prepare($sql);
$stmt->execute();
} catch(PDOException $e) {
echo "查詢失敗: " . $e->getMessage();
}
$conn = null;
$perPage = 10;
$currentPage = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$totalQuery = "SELECT COUNT(*) FROM myTable";
$totalResult = $conn->query($totalQuery);
$totalRecords = $totalResult->fetchColumn();
$totalPages = ceil($totalRecords / $perPage);
if ($currentPage < 1 || $currentPage > $totalPages) {
die("無效的頁碼");
}
for ($i = 1; $i <= $totalPages; $i++) {
echo "<a href='?page=" . $i . "'>" . $i . "</a> ";
}
通過以上方法,可以在分頁類的各個步驟中實現錯誤處理機制。在實際開發中,可以根據需要選擇合適的錯誤處理方式,例如記錄日志、發送通知等。