I am running drupal 6.22 with MySQL. There is no drupal 6 API for using transactions. Since I am new to drupal, I do not know which is the best way to use transactions using the existing drupal APIs? Can anyone guide me on this?
Transactions are done with SQL and in Drupal 6 you need to write all your SQL. So to use transactions, all you need to do, is to use
db_query(SQL) and include transaction in the SQL you create.
This could look like this:
$sql = 'START TRANSACTION; SELECT @A:=SUM(salary) FROM table1 WHERE type=1; UPDATE table2 SET summary=@A WHERE type=1; COMMIT;'; db_query($sql);
Remember to use an engine that supports transactions like
You can actually initiate a transaction with a db_query() run many db_query()'s and then either do a commit or rollback with another db_query() as in:
// start transaction db_query("START TRANSACTION"); // repeat the following as required db_query("SELECT ..."); db_query("UPDATE ..."); // end transaction db_query("COMMIT"); - or - db_query("ROLLBACK");
With this be very careful, you cannot return in the middle of your function without first making sure that you do a COMMIT or ROLLBACK. The safest way to do that is to create a transaction object and use RAII (i.e. the destuctor of that object makes sure one of COMMIT or ROLLBACK is sent).