PDO::commit() success or failure
mysql, pdo, php, transactions
Solution
The return value is based on pdo::commit itself, not the transaction you're trying to commit. It returns FALSE when there's no transaction active, but it's not very clear whenever it should return TRUE or FALSE.
The executed queries within the transaction itself will success or fail on it's own. Using the Mr.Tk's example, the transaction will be committed if possible and no error occured while executing the queries in the "try" block and rolled back if an error did occur within the "try" block.
When only evaluating the executed queries within the "try" block, personally I would try to catch a PDOException instead of a normal Exception.
$dbh->beginTransaction();
try {
// insert/update query
$dbh->commit();
} catch (PDOException $e) {
$dbh->rollBack();
}
Problem
The PHP PDO::commit() documentation states that the method returns TRUE on success or FALSE on failure. Does this refer to the success or failure of the statement executions between beginTransaction() and commit()? For example, from the documentation: ``` $dbh->beginTransaction(); $sql = 'INSERT INTO fruit (name, colour, calories) VALUES (?, ?, ?)'; $sth = $dbh->prepare($sql); foreach ($fruits as $fruit) { $sth->execute([ $fruit->name, $fruit->colour, $fruit->calories, ]); } $dbh->commit(); ``` If any of the above executions fail, will the commit() method return false due to the "all-or-nothing basis" of atomic transactions?