I really haven't found normal example of PHP file where MySQL transactions are being used. Can you show me simple example of that?
And one more question. I've already done a lot of programming and didn't use transactions. Can I put a PHP function or something in header.php
that if one mysql_query
fails, then the others fail too?
I think I have figured it out, is it right?:
mysql_query("SET AUTOCOMMIT=0");
mysql_query("START TRANSACTION");
$a1 = mysql_query("INSERT INTO rarara (l_id) VALUES('1')");
$a2 = mysql_query("INSERT INTO rarara (l_id) VALUES('2')");
if ($a1 and $a2) {
mysql_query("COMMIT");
} else {
mysql_query("ROLLBACK");
}
The idea I generally use when working with transactions looks like this (semi-pseudo-code):
Note that, with this idea, if a query fails, an Exception must be thrown:
PDO::setAttribute
PDO::ATTR_ERRMODE
andPDO::ERRMODE_EXCEPTION
Unfortunately, there is no magic involved. You cannot just put an instruction somewhere and have transactions done automatically: you still have to specific which group of queries must be executed in a transaction.
For example, quite often you'll have a couple of queries before the transaction (before the
begin
) and another couple of queries after the transaction (after eithercommit
orrollback
) and you'll want those queries executed no matter what happened (or not) in the transaction.Please check which storage engine you are using. If it is MyISAM, then
Transaction('COMMIT','ROLLBACK')
will not be supported because only the InnoDB storage engine, not MyISAM, supports transactions.One more procedural style example with
mysqli_multi_query
, assumes$query
is filled with semicolon-separated statements.