2017-02-27 133 views
0

我有一些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; 
} 
+0

檢查這裏:https://phpdelusions.net/pdo#errors –

回答

0
  1. 步驟:

這個代碼添加到頁面頂部:

error_reporting(E_ALL); 
ini_set("display_errors", 1); 
ini_set("display_startup_errors", 1); 

use error_reporting(E_ALL) only in development mode!

  1. 步驟

在您的$ conn = new PDO(...)後添加以下代碼;

$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
+0

$康恩已經被設置爲ERRMODE_EXCEPTION。不幸的是:( –

+0

那麼它的意思是:它沒有拋出一個致命的錯誤,並且你的error_handling級別太低了,讓我爲你修復它 –

+0

完成,但是除了catch塊之外,其實我的php.ini已經被配置爲報告錯誤。以下是來自php.ini的值: error_reporting = E_ALL&〜E_DEPRECATED&〜E_STRICT display_errors = On display_startup_errors = On –