PHP尝试捕获不捕获PDOException / Exception

时间:2017-02-27 11:39:06

标签: php pdo try-catch

我在 try catch 块中有一些PDO插入代码。我故意将错误的值传递给execute函数,以便插入失败。即; 在声明为主列的列上插入重复值。经过测试,插入查询在控制台上执行时失败,给出错误:

#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;
 }

2 个答案:

答案 0 :(得分:0)

  1. 步骤:
  2. 将此代码添加到页面顶部:

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

    仅在开发模式下使用error_reporting(E_ALL)!

    1. 步骤
    2. 在$ conn = new PDO(...);

      之后添加以下代码
      $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
      

答案 1 :(得分:0)

您可能需要包括PDOException例如

use PDO;
use PDOException;