简体   繁体   中英

Mysql Transactions practices

I have seen a couple examples of Transaction tutorial and all with this typical code

$this->db->trans_begin();

$this->db->query('WRITE TO TABLE A');
$this->db->query('WRITE TO TABLE B');
$this->db->query('WRITE TO TABLE c');
$this->db->query('WRITE TO TABLE D');
$this->db->query('WRITE TO TABLE E');

if ($this->db->trans_status() === FALSE)
{
        $this->db->trans_rollback();
}
else
{
        $this->db->trans_commit();
}

But I need do some block condition between them. Is possible to write something like this?

$this->db->trans_begin();

$this->db->query('WRITE TO TABLE A');

if(some_condition){    
   $this->db->query('WRITE TO TABLE B');
 }

$this->db->query('WRITE TO TABLE c');

if(some_other_condition){
 //Do some operations or calculations here and then write to database
  $this->db->query('WRITE TO TABLE D');
}

$this->db->query('WRITE TO TABLE E');

if ($this->db->trans_status() === FALSE)
{
        $this->db->trans_rollback();
}
else
{
        $this->db->trans_commit();
}

Is this possible?

Yes You can write a condition in between the database transaction. For More detail you should check the documentation-here

I will also suggest you that you should use error log and also use $this->db->last_query(); After each query to get the idea of query execution. It will be enough for getting what's going on with the database transaction.

If you want to explore more about this then you can try this also:

try {
  $this->db->trans_begin();
  $res = $this->db->query('AN SQL QUERY...');
  if(!$res) throw new Exception($this->db->_error_message(), $this->db->_error_number());
  $res = $this->db->query('ANOTHER QUERY...');
  if(!$res) throw new Exception($this->db->_error_message(), $this->db->_error_number());
  $this->db->trans_commit();
}
catch (Exception $e) {
  $this->db->trans_rollback();
  log_message('error', sprintf('%s : %s : DB transaction failed. Error no: %s, Error msg:%s, Last query: %s', __CLASS__, __FUNCTION__, $e->getCode(), $e->getMessage(), print_r($this->main_db->last_query(), TRUE)));
}

Please not that

  1. I am using the "manual transaction" mode of CI,
  2. I have to call $this->db->_error_message() , $this->db->_error_number() after each query, because it returned an empty response in the catch block. Only this way I can achieve the detailed error handling but I find it clunky.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM