With regards to using PHP's API for MySQL transaction support I was wondering about autocommit
.
For example, I'm not sure how it works by default, but ideally I would like all queries to auto commit unless I explicitly start a transaction with something like:
$db->begin_transaction();
$db->query(...);
$db->query(...);
$db->commit();
As a related question, I notice begin_transaction()
wasn't introduced until PHP 5.5 so is it possible to get behaviour before 5.5?
I know there is $db->autocommit()
but does that mean if I want the above behaviour I would need to have it on by default and then do $db->autocommit(false)
before any transactions and then $db->autocommit(true)
afterwards?
Here's the documentation on transactions and the autocommit
setting.
To quote from that documentation:
By default, MySQL runs with autocommit mode enabled. This means that as soon as you execute a statement that updates (modifies) a table, MySQL stores the update on disk to make it permanent. The change cannot be rolled back.
As I read this, the way it works is this:
Imagine you're making queries without using transactions. You do an INSERT
with autocommit on and that INSERT happens immediately (ie. is stored to disk right away). An UPDATE
? It happens immediately.
Now imagine you turn off autocommit
and make queries the same way. The quote above implies that if you perform that INSERT
command with autocommit
off, it is not immediately stored to disk. So what happens to that INSERT
? To quote from the documentation again:
After disabling autocommit mode by setting the autocommit variable to zero, changes to transaction-safe tables (such as those for InnoDB or NDBCLUSTER) are not made permanent immediately. You must use COMMIT to store your changes to disk or ROLLBACK to ignore the changes.
So, in short, using autocommit
is a different way of implementing transactions. In MySQL you can do this:
START TRANSACTION;
INSERT INTO table VALUES (1, 2, 3);
COMMIT;
or you can do this:
SET autocommit=0;
INSERT INTO table VALUES (1, 2, 3);
COMMIT;
Note too that there's an implicit commit when you change the autocommit
value - so doing this would be equivalent:
SET autocommit=0;
INSERT INTO table VALUES (1, 2, 3);
SET autocommit=1;
You can do things the same way in PHP, using either $db->begin_transaction();
or $db->autocommit(false);
to start the transaction, the doing $db->commit();
at the end. Personally, I find the begin_transaction
method clearer.