As already mentioned in other answers, begin_transaction()
starts a transaction, without affecting the value of autocommit
. The queries are not commited into the database until you call commit()
or trigger an implicit commit.
As described in MySQL docs:
A session that has autocommit enabled can perform a multiple-statement transaction by starting it with an explicit START TRANSACTION or BEGIN statement and ending it with a COMMIT or ROLLBACK statement. See Section 13.3.1, “START TRANSACTION, COMMIT, and ROLLBACK Statements”.
If autocommit mode is disabled within a session with SET autocommit = 0, the session always has a transaction open. A COMMIT or ROLLBACK statement ends the current transaction and a new one starts.
This means that the main difference between begin_transaction()
and autocommit(FALSE);
is whether you want a one-time transaction or whether you want contiguous transactions.
A simple one-time transaction using begin_transaction()
would look like this:
<?php
// Switch on error reporting with exception mode
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'username', 'password', 'db_name');
$mysqli->set_charset('utf8mb4');
try {
// Start transaction
$mysqli->begin_transaction();
$mysqli->query('INSERT INTO some_table(col2) VALUE(4)');
$mysqli->query('INSERT INTO some_table(col2) VALUE(4');
// Commit changes
$mysqli->commit();
} catch (\Throwable $e) {
// Something went wrong. Rollback
$mysqli->rollback();
throw $e;
}
Such approach is clearer than switching the autocommit mode off altogether. .