此 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/