Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when a PHP script accesses a MySQL database at the same time, more than once?

I was curious about how PHP scripts and MySQL behave? The script is basically two SQL queries.

The first SELECTs and gets a number from a column of a specific row decided by some id.

Then if the number is positive the second UPDATES the column by subtracting a certain amount.

Obviously this a classic case where I would use transactions or lock or mutexes or what on.

My questions is this: In a website it is entirely possible for two or more users to call the script at the same time for the same row. If you don't use transactions or lock tables how will PHP process this? They are two queries/function calls but they are in one script. Does it wait the whole script to return to it's corresponding user to run it again for another user or because they are different queries because of pseudoparallelism it might run the first query on multiple user calling the same script and then the second for a different set..

Basically I am asking because I am doing something where I don't have enough permissions to use transaction or locks and I want to know if I can a avoid a mutex (I am not sure about the word, basically a new table for callers; before calling the script above I will call a new script before that where I will turn the boolean column of the table true for writing so other people cant while the original script finishes and afterwards bacl to false so the next in line can do and so on)

Edit: I am not sure about select for update whether the permissions for that are included in the above mentioned. The guy responsible for answering my questions is hard to find and I ve had it with me searching for him...

like image 456
Andreas Andreou Avatar asked Nov 12 '22 11:11

Andreas Andreou


1 Answers

It's very strange that you can do update, but cannot lock table(update are locking table for some engines and locking rows for other). But if you really cannot lock that's way you may use get_lock function. It's work like mutex.

P.S. If you are using update with only assignment(set a=10) you can loose some data. If you using assignment with ref on the filed(set a=10+a) it's never happen.

like image 113
sectus Avatar answered Nov 15 '22 05:11

sectus