I need to be sure that the following works fine with PDO Transactions:

// Database Transaction
    // Start the transaction.

        // Some method in this class which runs a database query 

        // Another method doing multiple database queries

        // Directly doing some query
        $stmt = $db->prepare("DELETE FROM `table` WHERE `time` < DATE_SUB(NOW(), INTERVAL :days DAY)");
        $stmt->execute(['days' => 2]);

    // Commit

catch(Exception $e)
    $error = $e->getMessage();
    // log

    // Rollback the transaction.

My question is:

Will it roll back everything (including queries done in other methods) this way? or only the direct query?

1 Answers

Nigel Ren On Best Solutions

A transaction covers the database connection and not the unit of PHP code. So any query which uses that connection will be subject to the transaction.

You have to be careful that sometimes programmers will create their own database connections within (for example) a class constructor, which means the class methods may be using their own connection and therefore not subject to the transaction you are trying to control. This is also a reason for passing in database connections and not creating your own or using global.

Although you also have to be aware that certain SQL statements will cause commits etc. So refer to https://dev.mysql.com/doc/refman/5.6/en/sql-syntax-transactions.html which will give more details as to when/what/where these may happen.