PHP / MySQL - how to prevent two requests *Update

前端 未结 5 1304
清酒与你
清酒与你 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
    
    0 讨论(0)
  • 2020-12-23 22:22

    First off, you have to use transactions, but that's not enough. In your transaction, you can use SELECT FOR UPDATE.

    It's basically saying, "I'm going to update the records I'm selecting", so it's setting the same locks that an UPDATE would set. But remember this has to happen inside a transaction with autocommit turned off.

    0 讨论(0)
  • 2020-12-23 22:27

    you need to use TRANSACTION at the SERIALIZABLE isolation level.

    0 讨论(0)
  • 2020-12-23 22:31

    This is how I used to do it many years ago..

    results = query("UPDATE table SET value=value-5 WHERE value>=5 AND ID=1")
    if (results == 1) YEY!
    

    (Is this still a reliable method?)

    0 讨论(0)
  • 2020-12-23 22:47

    You need to use Data revision for MySQL UPDATE.

    0 讨论(0)
提交回复
热议问题