note 97247 deleted from function.PDO-beginTransaction by danbrown

From: Date: Sat, 10 Apr 2010 02:08:22 +0000
Subject: note 97247 deleted from function.PDO-beginTransaction by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-168098@lists.php.net to get a copy of this message
Note Submitter: FMaz ---- My case: ----------- I had a case where I needed to give "points" to user, then report the turn to the next day. I needed transaction for that because sometime, a second or third user was able to lauch the process between the time that the first user started, but before he completed the transaction. But in the process, the user(s) who receive point need to have a message added. The addMessage function use transaction, because I often have collision on the message table. Possible problematic transaction sheme: ---------- So, I was having this sheme: beginTransaction() //Give the "points" to all the selected users beginTransaction() //Add a message to user 1 commit() beginTransaction() //Add a message to user 2 commit() beginTransaction() //Add a message to user 3 commit() commit() The problem: ---------- So you might see: it's not working well, I have a double beginTransaction(). The solution: ---------- "drm at melp dot nl / 11-Feb-2008 09:37" gave me the idea. My solution is the same as him, but with a counter, so only the first beginTransaction() and the last commit() will be executed. class PDOPlus extends PDO { private $activeTransactionCount = 0; public function beginTransaction() { $this->activeTransactionCount++; if ( $this->activeTransactionCount > 1) return false; else return parent::beginTransaction (); } public function commit() { if($this->activeTransactionCount == 1) parent::commit (); $this->activeTransactionCount--; } public function rollback() { parent::rollback(); $this->activeTransactionCount = 0; } } I'm pretty sure it's not a good & recommended practice, so use it with caution, but I'm unable to figure out how to solve my specific problem in that specific case without doing complex modifications.

« previous php.notes (#168098) next »