| Transaction Wrapper [message #1233] |
Thu, 10 May 2007 05:03  |
Speeple Messages: 91 Registered: August 2006 |
Member |
|
|
Hi,
I've come across my first situation on a project that requires the usage of SQL transactions, I have a wrapper class for MySQLi in PHP that reduces and improves the readability of my code.
Here is the wrapper class for a transaction:
<?php public function transaction() {
$count = func_num_args();
if ($count) {
self::$SQL->autocommit(false);
$return = false;
for ($i = 0; $i < $count; $i++) {
if (($query = func_get_arg($i)) && !self::$SQL->query($query)) {
self::$SQL->rollback();
self::$SQL->autocommit(true);
return false;
}
}
if (self::$SQL->commit()) $return = true;
else self::$SQL->rollback();
self::$SQL->autocommit(true);
return $return;
}
else return false;
} ?>
I've been researching transactions and realised they are "all or nothing", meaning I could change the following lines from:
<?php for ($i = 0; $i < $count; $i++) {
if (($query = func_get_arg($i)) && !self::$SQL->query($query)) {
self::$SQL->rollback();
self::$SQL->autocommit(true);
return false;
}
} ?>
to:
<?php for ($i = 0; $i < $count; $i++) self::$SQL->query($query); ?>
And the outcome of the function would be the same (but better optimised and less code).
Would I be correct in assuming this?
Cheers!
Martin Gallagher | Speeple: The latest news
|
|
|
| Re: Transaction Wrapper [message #1241 is a reply to message #1233 ] |
Sat, 12 May 2007 07:13  |
Speeple Messages: 91 Registered: August 2006 |
Member |
|
|
After researching it a bit more I've come to the realisation a execution check on each query is not required as the trasnaction block is all-or-nothing resulting in the final function:
<?php public function transaction() {
$count = func_num_args();
if ($count) {
self::$SQL->autocommit(false);
$return = false;
for ($i = 0; $i < $count; $i++) if ($query = func_get_arg($i)) self::$SQL->query($query);
if (self::$SQL->commit()) $return = true;
else self::$SQL->rollback();
self::$SQL->autocommit(true);
return $return;
}
else return false;
} ?>
Martin Gallagher | Speeple: The latest news
|
|
|