Search code examples
phpmysqlsqltransactions

How to check if previous query was executed correctly?


I have to decrease money from a user account and increase another user account, namely to transfer money from an account to another. I have this code for example, in MySql:

START TRANSACTION;
UPDATE accounts
SET balance = (balance-100)
WHERE account_id = 2 AND balance>100;

--If the above query is succesfully then:
UPDATE accounts
SET balance = (balance+100)
WHERE account_id =1;

--How can I exec the commit only if everything is ok?
COMMIT;

The first query is executed only if the balance>100.

However the second query (namely the second update) should be executed only if the prevoious query has decreased the balance. How could I automatically check this?

Furthermore the COMMIT; has to be executed only if the previous 2 queries have done their job.

How could this be implemented?

(I'm using PHP too but I think this problem could easily tackled using sql. Am I wrong?)


Solution

  • Perform the operation as single query, not as a query pack:

    UPDATE accounts t1
    CROSS JOIN accounts t2
    SET t1.balance = (t1.balance-100),
        t2.balance = (t2.balance+100)
    WHERE t1.account_id = 2 AND t1.balance>100
      AND t2.balance_id = 1;
    
    -- or
    
    UPDATE accounts
    SET balance = balance + CASE account_id WHEN 1 THEN 100
                                            WHEN 2 THEN -100 END
    WHERE account_id IN (1,2);
    

    And you do not need in transaction at all.


    Also you may check the amount of rows altered (by fact, on disk, not formally) by previous query, and take this info into account in 2nd query:

    START TRANSACTION;
    
    UPDATE accounts
    SET balance = (balance-100)
    WHERE account_id = 2 AND balance>100;
    
    UPDATE accounts
    SET balance = (balance+100)
    WHERE account_id =1 
      AND ROW_COUNT();  -- check does a row was altered in previous statement
                        -- if not then this statement will not alter any row too
    
    COMMIT;