在PHP中處理MySQL數據庫異常情況,通常需要使用錯誤處理機制。這包括檢查執行SQL語句時是否發生錯誤,以及適當地處理這些錯誤。以下是一些處理MySQL異常情況的步驟:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// 創建連接
$conn = new mysqli($servername, $username, $password, $dbname);
// 檢查連接
if ($conn->connect_error) {
die("連接失敗: " . $conn->connect_error);
}
$sql = "SELECT * FROM myTable";
$result = $conn->query($sql);
if (!$result) {
die("查詢失敗: " . $conn->error);
}
if ($result->num_rows > 0) {
// 輸出每行數據
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 結果";
}
$conn->close();
$stmt = $conn->prepare("INSERT INTO myTable (name) VALUES (?)");
$stmt->bind_param("s", $name);
$name = "John";
if ($stmt->execute()) {
echo "新記錄插入成功";
} else {
echo "Error: " . $stmt->error;
}
$stmt->close();
function handleError($errno, $errstr, $errfile, $errline) {
echo "發生錯誤: [$errno] $errstr on line $errline in $errfile";
}
set_error_handler("handleError");
通過這些步驟,可以在PHP中有效地處理MySQL數據庫的異常情況,確保程序的健壯性和安全性。