Transaction handling with multiple mysqli object
08:29 30 Mar 2012

Lets put the case that we've got two separate classes, each owns a mysqli object to use for database operations.

class A{
  protected $mysqliObject;
  public function __constructor(){
    $this->mysqliObject=new mysqli(...)
  }
  public function doSomething(){
    $this->mysqliObject->query(...);
  }
}
class B{
  protected $mysqliObject;
  public function __constructor(){
    $this->mysqliObject=new mysqli(...)
  }
  public function doSomething(){
    $this->mysqliObject->query(...);
  }
}

The doSomething() methods use the $mysqliObject for a database query (SELECT, UPDATE, DELETE, etc...). I want to do the following outside:

// Start point
$aObject=new A();
$bObject=new B();
$aObject->doSomething();
$bObject->doSomething();
// End point

...but I want to roll back both queries if any of them fails. How can I do that?

  • Can I create a brand new mysqli object at "Start point", and use it to commit or rollback at "End point" the database query of class A and class B?
  • Do I have to create outside, and pass the same $mysqliObject to the __constructor() of class A and class B, and use that to rollback or commit (outside).

Would like to see more techniques with pro-con's.

php mysqli transactions