Transactions
Transactions ensure that a group of database operations are executed as a single atomic unit. If one step fails, all changes are rolled back automatically. Use startTransaction(), commit() and rollback() for reliable updates.
Methods:
public function startTransaction(): voidpublic function commit(): voidpublic function rollback(): void
Basic Usage
try {
$db->startTransaction();
$insertData = [
'email' => 'new@example.com',
'created_at' => $db->now()
];
$db->insert('test_users', $insertData);
$db->commit();
} catch (\Throwable $e) {
$db->rollback();
error_log("Transaction failed: " . $e->getMessage());
}
Notes
- Always wrap
startTransaction()/commit()/rollback()in logical control blocks - If a transaction is already active, a second call to
startTransaction()will be ignored - If
rollback()orcommit()is called without an active transaction, an exception will be thrown - Transactions only work on tables using
InnoDB