So here is my scenario, lets assume I am making an online shopping platform. And My User have a balance of 100
in the user_balance
field or table.
Now, the user, open both the withdrawal page
which let them withdraw money
and a shopping page
which let him to buy a watch of 100 dollar with one click
Let say the user withdraw 100 dollar and buy a watch for 100 dollar at the same time.
My question is will the SELECT user_balance FROM balances FOR UPDATE
execute at the same time or it will wait other to finish select.
If both the SELECT...FOR UPDATE
execute at the same time, the user_balance
will show 100
for both page and thus, it will allow withdrawal of 100
and purchase a watch for 100
and hence, when we finally update the balance of the user it will show a negative balance
100(user balance) - 100(withdrawal amount) - 100(purchasing of watch) = -100
Here is concept of code of both pages:
Withdrawal Pages:
$withdrawal_amount = 100;
$user_balance = "SELECT user_balance FROM balances FOR UPDATE"; //actually return 100?(not sure about it, that is what my question about)
if($user_balance > $withdrawal_amount){
//allow withdrawal
$update_sql_query = "UPDATE balances SET user_balance = user_balance - " . $withdrawal_amount;
}
Purchase Watch Page:
$product_subtotal = 100;
$user_balance = "SELECT user_balance FROM balances FOR UPDATE"; //actually return 100?(not sure about it, that is what my question about)
if($user_balance > $product_subtotal){
//allow withdrawal
$update_sql_query = "UPDATE balances SET user_balance = user_balance - " . $product_subtotal;
}