1
votes

I'm trying to get my head around PDO transactions to commit a fairly complex set of MySQL queries at once. When I run the transaction however, it will commit one query and not the other - if there is a single error in either query I expect it to roll back both queries and not make changes to either table.

So far: My connect.php file:

class DbConnect {
    private $conn;
    function __construct() {        
    }
    /**
     * Establishing database connection
     * @return database connection handler
     */
    function connect() {
        //Where HOST, USER, PASS etc are set
        include_once "./dbconfig.php";

        // Establish the connection
        try {
        $this->conn = new PDO("mysql:host=".HOST.";dbname=".DBNAME, USER, PASS); 
        $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $this->conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

        return $this->conn;
        } catch (PDOException $e) {
            print "Error!: " . $e->getMessage() . "<br/>";
            die();
        }
    }
}

My file where I'm trying to pass the simultaneous SQL queries

    public function transaction ($userId, $amount){
        //Creates the PDO connection EDIT: added my DB connection
        $db = new DbConnect();
        $this->conn = $db->connect();

        $con = $this->conn;

            $con->beginTransaction();
            try{
                $sql = "INSERT INTO transactions (id_user, amount) VALUES (?, ?)";
                $trans = $con->prepare($sql);
                $trans->execute([$userId, $amount]);
                //If I purposely create an error here the query above still runs in the database e.g. remove the $amount variable
                $this->updateBalance($userId, $amount);
                $con->commit();
                return true;
            }
            catch (PDOException $e) {
                $con->rollBack();
                throw $e;                    
            }
    }

    private function updateBalance ($userId, $amount){
            $time = time();
            $sql = "UPDATE balance SET balance=balance + ? WHERE user_id = ?";
            $stmt = $this->conn->prepare($sql);
            $stmt->execute([$amount, $userId]);
            $row_count = $stmt->rowCount();
            return $row_count > 0;
        }

The above is just a small sample of a bigger more complex procedure otherwise I'd just put the balance query in the same place as the transaction, however I need to keep it in a separate function. Any ideas how I can get this into an "All or nothing" commit state?

1
Issue lies in what you didnt post, not in this sample. - Hanky Panky
@Hanky Added my PDO connection procedure - does that help? I have distilled my code to exactly as above - and passing the updateBalance function with 1 parameter (to create an error) - the first query still runs though - contool

1 Answers

0
votes

Well first of all you are not checking the return status of the call to your second function

$this->updateBalance($userId, $amount);

So how will you know there is an error even if there is one?

If you make that called function Throw an exception rather than returning a status, it should be caught by the calling blocks catch() block causing the rollback() and not the commit()

Something like this

public function transaction ($userId, $amount){
    //Creates the PDO connection
    $con = $this->conn;

    $con->beginTransaction();
    try{
        $sql = "INSERT INTO transactions (id_user, amount) VALUES (?, ?)";
        $trans = $con->prepare($sql);
        $trans->execute([$userId, $amount]);
        // If I purposely create an error here the 
        // query above still runs in the database 
        // e.g. remove the $amount variable
        $this->updateBalance($userId, $amount);
        $con->commit();
        return true;
    }
    catch (PDOException $e) {
        $con->rollBack();
        throw $e;
        return false;
    }
}

/*
* If this function throws an exception 
* rather than returning a status, then it will
* stop execution of the try block and
* be caught by the calling blocks catch() block
*/
private function updateBalance ($userId, $amount){

    $sql = "UPDATE balance SET balance=balance + ? WHERE user_id = ?";
    $stmt = $this->conn->prepare($sql);
    $res = $stmt->execute([$amount, $userId]);
    if ( ! $res ) {
        throw new Exception('It errored');
    }

}

Alternatively you could make all PDO calls throw exceptions by setting PDO::ERRMODE_EXCEPTION just after you connect to your database.

$dbh = new PDO($dsn, $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

However, this may be to major a change to PDO's error processing depending on how much code you have already produced.