ADOdb Library for PHP Manual
Prev BeginTrans Next

BeginTrans( )

Begin a transaction. Turns off autoCommit. Returns true if successful. Some databases will always return false if transaction support is not available. Among the databases that support transactions are Oracle, PostgreSQL, Interbase, MSSQL, certain versions of MySQL, DB2, Informix, Sybase, etc. Any open transactions will be rolled back when the connection is closed.

The following is the wrong way to use transactions:

    $DB->BeginTrans();
    
$DB->Execute("update table1 set val=$val1 where id=$id");
    
$DB->Execute("update table2 set val=$val2 where id=$id");
    
$DB->CommitTrans();

because you perform no error checking. It is possible to update table1 and for the update on table2 to fail. Here is a better way:

    $DB->BeginTrans();
    
$ok = $DB->Execute("update table1 set val=$val1 where id=$id");
    if (
$ok) $ok = $DB->Execute("update table2 set val=$val2 where id=$id");
    if (
$ok) $DB->CommitTrans();
    else
$DB->RollbackTrans();

Another way is (since ADOdb 2.0):

    $DB->BeginTrans();
    
$ok = $DB->Execute("update table1 set val=$val1 where id=$id");
    if (
$ok) $ok = $DB->Execute("update table2 set val=$val2 where id=$id");
    
$DB->CommitTrans($ok);

You can also use the ADOdb error handler to die and rollback your transactions for you transparently. Some buggy database extensions are known to commit all outstanding tranasactions, so you might want to explicitly do a $DB->RollbackTrans() in your error handler for safety.


Prev Home Next
Smart Transactions Up CommitTrans

Sponsored by phpLens