Closed
Description
Description
The following code:
<?php
// Step 1: Perform a query
$sql = "SELECT 1 FROM anytable ROWS 1";
$statement = $pdo->prepare($sql);
$statement->execute();
$result = $statement->fetch(PDO::FETCH_ASSOC);
// Step 2: Perform a query in transaction
$pdo->beginTransaction(); // Fatal error on this line: Uncaught PDOException: There is already an active transaction
$statement = $pdo->prepare($sql);
$statement->execute();
$result = $statement->fetch(PDO::FETCH_ASSOC);
$pdo->commit();
Resulted in this output:
Fatal error: Uncaught PDOException: There is already an active transaction in ...
But I expected this output instead:
No exception. This works fine with mysql PDO. The manual says:
Turns off autocommit mode. While autocommit mode is turned off, changes made to the database via the PDO object instance are not committed until you end the transaction by calling PDO::commit(). Calling PDO::rollBack() will roll back all changes to the database and return the connection to autocommit.
It does not turn off autocommit. The workaround is to turn off autocommit manually before calling begintransaction and switching it on again after commit or rollback:
$pdo->setAttribute(PDO::ATTR_AUTOCOMMIT, false);
$pdo->beginTransaction();
// Do database stuff
$pdo->commit();
$pdo->setAttribute(PDO::ATTR_AUTOCOMMIT, true);
PHP Version
PHP 7.4 & 8.1.6
Operating System
No response