2017-02-27 136 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 –