我有一些PDO插入代碼試試catch block。我故意將錯誤的值傳遞給execute函數,以便插入失敗。即; 在聲明爲主要的列上插入重複值。經測試,插入查詢在控制檯上執行時失敗,提示錯誤:PHP try catch不抓PDOException /異常
#1062 - Duplicate entry '0' for key 'PRIMARY'
但是,我的try-catch塊沒有捕捉到這個異常。是否因爲PHP不會爲重複條目拋出異常?我是PHP新手。一直在尋找的淨,但似乎無法找到一個線索:
try
{
$query = $conn->prepare($preSQL);
$query->execute($postSQL); //$postSQL is the associative array for placeholders
$dataAdded = $query->rowCount();
$lastInsertId = $this->conn->lastInsertId();
}
catch(PDOException $e)
{
fwrite($myfile,PHP_EOL);
fwrite($myfile,$e->getMessage());
fclose($myfile);
return false;
}
檢查這裏:https://phpdelusions.net/pdo#errors –