Announcement

Announcement Module
Collapse
No announcement yet.

Transaction Wrapper

Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Transaction Wrapper

    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:

    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:

    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:

    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!

  • #2
    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:

    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;
    }
    ?>

    Comment

    Working...
    X