PDO::inTransaction

(PHP 5 >= 5.3.3, Bundled pdo_pgsql, PHP 7, PHP 8)

PDO::inTransaction 检查是否在一个事务内

说明

PDO::inTransaction ( ) : bool

检查驱动内的一个事务当前是否处于激活。此方法仅对支持事务的数据库驱动起作用。

参数

此函数没有参数。

返回值

如果当前事务处于激活,则返回 true ,否则返回 false

User Contributed Notes

Anonymous 10-Aug-2020 07:27
In addition to what jlh says,
even with SQLite3 which automatically starts transaction,
inTransaction() only works after beginTransaction().

<?php
try{

   
$pdo = new PDO('sqlite:test.sql3', null, null, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
   
var_dump($pdo->inTransaction());echo "<br>";    // bool(false) : before beginTransaction()
   
$pdo->beginTransaction();
   
var_dump($pdo->inTransaction());echo "<br>";    // bool(true)  : after beginTransaction()
   
$pdo->rollBack();
   
var_dump($pdo->inTransaction());echo "<br>";    // bool(false) : after commit() or rollBack()

}catch (PDOException $e){

    echo
'PDOException: ' . $e->getMessage();

}catch (
Exception | ErrorException $e){

   
var_dump($e);

}
jlh 05-Jun-2020 02:50
Important note: This will only detect whether a transaction has been started using beginTransaction(). It will not be able to detect transactions started by any other means, for example by executing "START TRANSACTION".
christopeh at xhaleera dot com 18-Nov-2013 10:26
On OS X 10.9 with PHP 5.4.10, this function seems to correctly return bool(true) or bool(false) and not anymore integers.
r. hanouwer 19-Apr-2012 06:12
Exceptions regarding existing active transactions were thrown while I was almost certain sufficient checks were in place.
However, I quickly found out that a strict boolean comparison to PDO::inTransaction() was failing.

Using var_dump I learned that this function was returning integers, not boolean values.

var_dump(PDO::inTransaction()); // int(1) || int(0)
ron korving 13-Jan-2011 09:20
This method actually seems to work fine on PHP5.3.5 (and probably a few older versions).