PHP PDO try catch block 没有捕获

标签 php mysql pdo

此 PHP PDO try catch block 未捕获任何错误。这是为什么?我做错了吗?

try {    
    $this->connect();      
    $preparedQuery = $this->pdo->prepare($sql);
    $this->pdo->beginTransaction();
    $preparedQuery->execute();
    $lastInsertId = $this->pdo->lastInsertId();
    $this->pdo->commit();
    return $lastInsertId;

} catch (PDOException $e) {
    $this->pdo->rollBack();
    return "error";
}

我正常运行,但出现这个错误

Fatal error: Call to a member function rollBack() on null 

PDO对象

private function connect() {
        $this->pdo = new PDO('mysql:host=' . $this->host . ';dbname=' . $this->database . '', $this->username, $this->password);
        $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }

这是我的完整连接类。

class ConnectionModel {

    private $host;
    private $username;
    private $password;
    private $database;
    private $pdo;

    function __construct() {
        $this->host = 'localhost'; // database server address
        $this->username = 'myuser'; //database server username;
        $this->password = 'mypass'; //database server password;
        $this->database = 'oms1'; //database name
    }

    private function connect() {
        $this->pdo = new PDO('mysql:host=' . $this->host . ';dbname=' . $this->database . '', $this->username, $this->password);
        $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }


    public function runQuery($sql) {

        try {

            $this->connect();
            $preparedQuery = $this->pdo->prepare($sql);
            $this->pdo->beginTransaction();
            $preparedQuery->execute();
            $lastInsertId = $this->pdo->lastInsertId();
            $this->pdo->commit();
            return $lastInsertId;
        } catch (PDOException $e) {
            $this->pdo->rollBack();
            return $e->getMessage();
        }
    }

}

最佳答案

您的问题是,您没有捕获到任何连接异常。所以你必须这样做:

private function connect() {
    try {
        $this->pdo = new PDO('mysql:host=' . $this->host . ';dbname=' . $this->database . '', $this->username, $this->password);
        $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch(PDOException $e) {
        echo $e->getMessage();
    }
}

现在你在 try 和 catch block 中调用你的连接方法,所以在你的方法中连接将抛出一个异常,然后从你的 try 和 catch block 中捕获它,它也有 rollBack 调用,但期望连接成功。

如果您将连接调用放在 try 和 catch block 之外,您将得到一个未捕获的异常:

$this->connect();
try {

} catch(PDOException $e) {
    $this->pdo->rollBack();
    return $e->getMessage();
}

关于PHP PDO try catch block 没有捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30585559/

相关文章:

php - 随机选择与之前选择的记录不同的记录

php - 按比例在图片上写文字

mysql - 使用 WHERE 和 GROUP BY 进行查询的最有效索引?

Mysql/Mysqli/PDO 性能 - 我打印的表或表的数量

php - PDO 功能错误

mysql - MySQL 中不同日期的两个时间之间的差异

php - AWS ElasticBeanstalk ENV Vars 不工作

php - 查询与不同表关联的值的相似结果 (LIKE %..%)

php - 如何用php发送html邮件

mysql - 如何删除数据库中MySQL表中的相关数据?