colshrapnel / safemysql

A real safe and convenient way to handle MySQL queries.
Apache License 2.0
395 stars 197 forks source link

how to use transaction? #43

Closed haningu closed 6 years ago

haningu commented 7 years ago

is possible?? Thanks.

rotate4all commented 6 years ago

Yeah, I'm also interested in this. I've been using this class since last year and I love it. Would also implement transactions on some queries. So does it support transactions?

EDIT: So to answer my own doubt and perhaps others', YES it does support TRANSACTIONS and here's how to do it:

$db->query("START TRANSACTION");  

//do all other queries here

$db->query("COMMIT"); 

Works like a charm. Tested.

colshrapnel commented 6 years ago

Yes, it's possible, using generic mysql commands.

Here is a brief example:

$db->query("create table trans_test (i int) ENGINE=InnoDB");

try {
    $db->query("BEGIN");
    $db->query("insert into trans_test VALUES (1)");
    $db->query("insert into trans_test VALUES (1)");
    $db->query("insert into trans_test_nonexistent VALUES (1)");
    $db->query("COMMIT");
} catch (\Throwable $e) {
    $db->query("ROLLBACK");
    throw $e;
}

This code when run as is will produce an error and no records will be added. With the 3rd insert query commented out it will make 2 inserts recorded.

If your transaction is still not working please check out the transactions checklist, which is written for PDO but applicable for any driver as well: https://phpdelusions.net/pdo#transactions