Skip to content
Advertisement

How to block table in booking?

How to block table to booking? My booking table has from_datetime and to_datetime fields. I would like to avoid situation, when two users book something in the same time.

My attempts:

TERMINAL 1: – user1

Now table booking should be locked, and other users should not be able to read from its, but…

TERMINAL 2: – user2

I have results… Why? This should be blocked until I do in TERMINAL 1:

Advertisement

Answer

You need to use LOCK TABLE booking WRITE;. That indicates that you’re going to be writing to the table, and you need to block everyone else from reading and writing the table.

A READ lock means that you’re only going to read the table. It blocks other users from writing to the table, so that all your reads access consistent table contents. But it doesn’t block other users from reading the table.

However, if you’re using InnoDB you should use transactions rather than table locks. This is more fine-grained, and figures out what to lock automatically. Your code would look something like this:

The FOR UPDATE option in the SELECT causes MySQL to lock the appropriate part of the table. If another user executes the same code, they’ll be blocked if they try to select the same times.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement