Ted Whalen Tue Apr 19 14:51:28 -0400 2011

Subject: DB Transactions in PHP ActiveRecord

Does anyone have an example of a working DB Transaction using PHP-ActiveRecord on the connection level? The only examples I see use Models = (1 table). Why would anyone want to use a transaction for inserting into 1 table? I suppose if you inserting lots of rows but I usually use transactions to ensure ALL CHANGES or NO CHANGES take place across multiple tables (and sometimes across multiple connections).

In PDO: ===========
$databaseconn->beginTransaction();

try{
SQL
SQL
SQL

$databaseconn->commit();
}catch(Exception $e){
$databaseconn->rollback();
}


Ted Whalen Tue Apr 19 17:16:21 -0400 2011

I need to update multiple databases over multiple connections. This is easily accomplished in PDO.

I would like to:

$dbconn1->beginTransaction();
$dbconn2->beginTransaction();

try{
SQL - Conn1_db1
SQL - Conn1_db2
SQL - Conn2_db1
SQL - Conn2_db2

$dbconn1->commit();
$dbconn2->commit();

}catch(Exception $e){

$dbconn1->rollback();
$dbconn2->rollback();
}

Ted Whalen Tue Apr 19 19:19:05 -0400 2011

Ok, well I did find 1 solution to this. It's a bit "hacky" but it does work.
<----METHOD REMOVED SO AS NOT TO CONFUSE OTHERS----->

Yoan B Thu Apr 21 03:10:18 -0400 2011

Did you take a look at how transactions are wrapped?

http://www.phpactiverecord.org/docs/ActiveRecord/Model#methodtransaction
https://github.com/kla/php-activerecord/blob/master/lib/Model.php#L1837

 1 // These models are using different connections.
 2 $c1 = Customer::connection();
 3 $c2 = AccountingCustomer::connection();
 4 
 5 try {
 6     $c1->transaction();
 7     $c2->transaction();
 8     // SQL…
 9     // SQL…
10     // SQL…
11     $c1->commit();
12     $c2->commit();
13 } catch (\Exception $e) {
14     $c1->rollback();
15     $c2->rollback();
16     throw $e;
17 }
Ted Whalen Thu Apr 21 18:08:21 -0400 2011

Now THAT's a working example. Thank you very much!!! Feels good to do this the way it was intended. No error, perfect COMMIT/ROLLBACK functionality.

(1-4/4)