PHP and MySQL: Running transactions yourself?
The idea of using transactions in MySQL is good. The idea of being able to rollback a transaction if something goes wrong is also good.
My question is this: In an application, is it worth it to control the transaction myself, or let MySQL take care of it for me? In other words, should have an active distrust of the autocommit feature that MySQL gives me?
Example:
try
{
$mysqli->autocommit( 0 );
//Normally, would go through the steps of prepping and executing etc,
//but I'll use this for brevity.
if( !$mysqli->query( ".." ) )
throw new Exception( ".." );
$mysqli->commit( )
}
catch( Exception $e )
{
$mysqli->rollback( ); //Doing this so I make sure I get my rollback
error_log( ".." );
}
instead of letting the autocommit feature do it's own handy work.
Notes: The application I'm writing is only set up to run one query at a time, there will be no situations (like in some (most) bank and other financial appli开发者_开发技巧cations) where I'll need to make sure two queries that change data, succeed.
This is mainly borne out of a want to control that kind of stuff (and a certain lacktherof in the autocommit feature).
As so often the answer is: it depends. If you want to ensure that
update(x);
update(y);
is atomic, i.e. both updates or none are executed, you should switch off auto-commit. If you are doing just one query, there'll be no need to control transactions yourself. If your only transaction fails, there'll be nothing to roll back, right?
On a related note: you might want to read about the ACID properties of transactions.
精彩评论