Andrew
Andrew

Reputation: 238707

How to impliment a "read then write lock" in MySQL?

I have a PHP application using a MySQL database. I would like to prevent two requests from performing the same (duplicate) action.

I would like to set a field on the record so that the first request can set it to true and let the other requests know that it is "currently being processed".

if ($currentlyBeingProcessed) {
    //get out of here
} else {
    //lock the row for processing
}

I realized that I could get into a situation where the two requests are so close in time that they could both read that record is "not being processed" before the first request could write to the database that it is "currently being processed".

Is there a way in MySQL to lock the row from other requests reading it until the first request has successfully finished writing to the database? How would I accomplish this?

Upvotes: 0

Views: 611

Answers (1)

Frank Heikens
Frank Heikens

Reputation: 127086

SELECT ... FOR UPDATE might be what you're looking for.

Upvotes: 2

Related Questions