php - PDO Multiple queries: commit and rollback transaction -


i need fire 2 queries. i'm doing this:

// begin transaction $this->db->begintransaction();  // fire queries if($query_one->execute()){     if($query_two->execute()){          // commit when both queries executed         $this->db->commit();     }else{         $this->db->rollback();    } }else{     $this->db->rollback(); } 

is correct approach? i'm not using try..catch in code make code inappropriate or vulnerable situation?

yes, approach correct. using try...catch may lead cleaner , more readable code in cases overall approach fine.

if code fragment function handles db queries , not else, i'd switch approach around:

// begin transaction $this->db->begintransaction();  // fire queries if(!$query_one->execute()){     $this->db->rollback();     // other clean-up goes here     return; }  if(!$query_two->execute()){     $this->db->rollback();     // other clean-up goes here     return;  }  $this->db->commit(); 

of course, if require lots of clean-up done before can return, original approach better. in these cases i'd using pdo::errmode_exception. has additional benefits, exceptions automatically rolling transaction unless caught.


Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -