ro ko
ro ko

Reputation: 2986

Suggestion, php mysql transaction for insertion to multiple tables in a block

I need to use transaction for a block of code, it consists of multiple insertions. Is it a good practice to have whole block of code within a try catch block, start transaction before the try..catch block. Then for any exception caught rollback the transactions else commit.

Basic question:

Here's a block of code:

    $con = Propel::getConnection(SomeTablePeer::DATABASE_NAME);        
    $con->beginTransaction();        
    try {
        $currentRevision = $budgetPeriod->getRevision();
        $newRevision = $currentRevision->copy();
        $newRevision->setIdclient($client->getIdclient());            
        $newRevision->setIsLocked(0);
        $newRevision->save();
        $currentRevision->setEffectiveTo($currentDate);
        $currentRevision->save();

        $currentRevisionHasCorporateEntities = $currentRevision->getCorporateEntitys();
        $newOldCorporateEntitiesRelations = array(); 

        foreach ($currentRevisionHasCorporateEntities as $currentRevisionHasCorporateEntity) {

            $newRevisionHasCorporateEntity = $currentRevisionHasCorporateEntity->copy();                
            $newRevisionHasCorporateEntity->save();
        }

     // this continues for a while there are a whole list of insertions based on previous insertion and on and on.
    }catch (Exception $exc) {
        $con->rollback();            
        $this->getUser()->setFlashError('Error occured! Transaction Failed');
    }

Upvotes: 1

Views: 285

Answers (2)

Shamis Shukoor
Shamis Shukoor

Reputation: 2515

The thing to be noted here is that how ever big the try block be, we should be able to catch the exceptions thrown by it and take actions accordingly.

But here you have used

catch (Exception $exc)

you will not be able to catch different exceptions. This is helpful to debug and show the correct reason for the exception.

Also if its a transaction, we have to have it in a single try block

Upvotes: 1

Vardan Gupta
Vardan Gupta

Reputation: 3585

Actually, We should focus on smaller transaction boundaries so that we can avoid any locks if occurs in Db but sometimes we need whole block of code to either executed or not, so in that case we hardly have any chances left with us, you need to modularize your code as much as possible.

Upvotes: 1

Related Questions