下面的代码有效,虽然在运行事务时我创建了另一个PDO对象,但这并不会影响我的事务:
$dsn = 'mysql:host=' . "localhost" . ';dbname=' . "somedb";
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_ORACLE_NULLS => PDO::NULL_TO_STRING
);
// first PDO object
$db = new \PDO($dsn, "someuser", "somepass", $options);
$db->beginTransaction();
$stmt = $db->prepare("INSERT INTO vbclient set company = 'test'");
$stmt->execute();
// second PDO object
$dbnew = new \PDO($dsn, "someuser", "somepass", $options);
$newstmt = $dbnew->prepare('select * from vbclient where clientID = 1');
$newstmt->execute();
$stmt = $db->prepare("INSERT INTO vbclient set company = 'test2'");
$stmt->execute();
$db->commit();
但是如果我将第二个PDO对象的创建放入一个单独的函数中,它似乎会终止第一个PDO对象的事务:
$dsn = 'mysql:host=' . "localhost" . ';dbname=' . "somedb";
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_ORACLE_NULLS => PDO::NULL_TO_STRING
);
// first PDO object
$db = new \PDO($dsn, "someuser", "somepass", $options);
$db->beginTransaction();
$stmt = $db->prepare("INSERT INTO vbclient set company = 'test'");
$stmt->execute();
secondPDO();
$stmt = $db->prepare("INSERT INTO vbclient set company = 'test2'");
$stmt->execute();
$db->commit();
function secondPDO() {
$dsn = 'mysql:host=' . "localhost" . ';dbname=' . "somedb";
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_ORACLE_NULLS => PDO::NULL_TO_STRING
);
// second PDO object
$dbnew = new \PDO($dsn, "someuser", "somepass", $options);
$newstmt = $dbnew->prepare('select * from vbclient where clientID = 1');
$newstmt->execute();
}
我收到错误“没有活动的交易。”我知道如果我用另一个实例覆盖PDO句柄,通常会发生这种情况。但我不这样做,只有当第二个PDO对象在另一个函数中时才会出现错误。
为什么会这样? 感谢。