I have a high traffic PHP site (lots of concurrent visitors) that uses MySQL for persistence. The site can be used to purchase various gift cards.
The controller in PHP handles purchases like this:
Step 1
SELECT id, reference_number, card_number FROM cards WHERE category_id = 3 AND card_case = 'unused' ORDER BY id ASC LIMIT 1;
+---------+------------------+------------------+
| id | reference_number | card_number |
+---------+------------------+------------------+
| 3324791 | 11556267335 | 0638570501 |
+---------+------------------+------------------+
Step 2
INSERT INTO orders (date_created, card_id, price, client_id) values ('2021-09-08 06:40:55', 3324791, 110.00, 7);
Step 3
UPDATE cards SET card_case = 'used' WHERE id = 3324791;
The problem: When there are lots of visitors to the site, there can be multiple "simultaneous" purchases (at least, within the same second) for the same category of card. This means that different clients end up taking the same card. How can I change the query in Step 1 so that the row returned is unique, and not returned for other clients (so that there are no duplicate purchases for the same card id)?