PHP / MySQL - how to prevent two requests *Update

前端 未结 5 1337
清酒与你
清酒与你 2020-12-23 22:02

I have some question ... example: a user will buy something for his USD

  1. Check his USD Balance
  2. Deduct the USD from his account
  3. Make an Order -
5条回答
  •  悲&欢浪女
    2020-12-23 22:21

    Use TRANSACTION and if it fails you can rollback.

    For example, assume the current balance is $20.

    Connection A               Connection B
    =======================    ===========================
    BEGIN TRANSACTION         
                               BEGIN TRANSACTION
    SELECT AccountBalance  
                               SELECT AccountBalance
    --returns $20
    --sufficient balance,
    --proceed with purchase
                               --returns $20
                               --sufficient balance,
                               --proceed with purchase
    
                                --update acquires exclusive lock
                               UPDATE SET AccountBalance
                                  = AccountBalance - 20
    --update blocked due
    UPDATE SET AccountBalance
      = AccountBalance - 20
    
                               --order complete
                               COMMIT TRANSACTION
    
    --update proceeds
    
    --database triggers
    --constraint violation
    --"AccountBalance >= 0"
    
    ROLLBACK TRANSACTION
    

提交回复
热议问题