I'm working on php + mysql project where we use a balance column that is used to keep track of a user's balance. Whenever a user makes a purchase their balance gets deducted. However I am trying to figure out what the best way is to tackle multiple requests from the same user when trying to purchase a product. I've done some research and wrote the following 2 approaches, I don't quite see a difference here could anyone explain what the difference between those 2 approaches is and which one is best regarding concurrency?
Approach 1:
START transaction
"SELECT balance from users where user_id = 1 FOR UPDATE"
check if balance - product price is enough then UPDATE
commit
Approach 2:
"UPDATE users set balance = balance - 30 where user_id = 1 AND balance - 30 >= 0"
As you can see option 2 is way less code, but I still see a lot of people recommending the first approach (locking the row first and then update).
Could anyone help me understand what actually the difference here is and which one is best to use when you care about concurrency and want to avoid multiple requests possibly making the balance column invalid? If you have better approaches please let me know, maybe I am overthinking the situation. I am using PDO.