【问题标题】:PHP try catch not catching PDOException/ExceptionPHP 尝试捕获未捕获 PDOException/异常
【发布时间】:2017-02-27 11:39:05
【问题描述】:

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

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

【问题讨论】:

标签: php pdo try-catch


【解决方案1】:
  1. 步骤:

将此代码添加到页面顶部:

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

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

  1. 步骤

在 $conn = new PDO(...); 之后添加以下代码

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

【讨论】:

  • 那么它的意思是:它没有抛出致命错误并且你的error_handling级别太低。让我帮你解决
  • 完成。仍然例外是转义 catch 块。实际上我的 php.ini 已经配置为报告错误。以下是 php.ini 中的值: br>error_reporting=E_ALL & ~E_DEPRECATED & ~E_STRICT br> display_errors=On br> display_startup_errors=On
【解决方案2】:

您可能需要包含 PDOException,例如

use PDO;
use PDOException;

【讨论】:

    猜你喜欢
    • 2014-05-11
    • 2011-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-02
    • 1970-01-01
    相关资源
    最近更新 更多