Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can two or more queries be executed at the very same time?

Ok, let's say we have bank_account table. There is a row called money. It has 2,000 value. And we have two persons trying to withdraw that money, let's suppose they can do it. So, is it possible that they would do it at the same time? For example. there is a made-up code:

 $all_money = get_value('money', 'bank_account); //lets suppose thats a function how we get value money from bank_account table

 if($all_money > 0) 
 {
     //here is a code where those money are being withdrawed from bank_account and inserting into the person's account
 }

If those two persons get value 2,000 at the same time then it means this clause if($all_money > 0) will be executed and both players will get 2,000 and bank_account will have -2,000 value of money. So, is it possible to happen? If yes, then how could I protect it? Thank you.

like image 638
good_evening Avatar asked Dec 12 '22 20:12

good_evening


1 Answers

Execute this before accessing the table:

LOCK TABLE table_name READ;

That will lock the table. When you have finished doing the work, you call:

UNLOCK TABLES;
like image 84
Cristian Avatar answered Dec 15 '22 11:12

Cristian