I'm stuck with this. To make it simpler, let's say I have this table
CREATE TABLE IF NOT EXISTS `tbl_bags_oranges` (
`idbag` int(11) NOT NULL AUTO_INCREMENT,
`n_oranges` int(11) NOT NULL,
PRIMARY KEY (`idbag`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci AUTO_INCREMENT=1 ;
And I'm developing a php script that represents the situation in which users grab oranges. This is what I'm doing:
- I use a
SELECT
to check if there are oranges in the given idgab (n_oranges > 0) - If so, I
UPDATE
the table subtracting 1 to n_oranges
But it may happen the following when there is just one orange in a bag:
- User A wants to grab an orange. The ´SELECT´ says there is one orange.
- User B wants to grab an orange. The ´SELECT´ says there is one orange.
- User A grab the orange. I
UPDATE
the table and now n_oranges = 0. - User B is able to grab the orange because his
SELECT
said that there was one orange.
How can I solve this question? Transactions? LOCK TABLES
? Since I can't check this situation there is no way to know if I'm doing well or wrong.