Menu

Issue unique queue numbers in PHP and MySQL without duplicates
📰

Issue unique queue numbers in PHP and MySQL without duplicates

DEV Community: mysql·Murabyte·3 days ago
#M6QK1VXT
#devtomysql#devto#dev#mysql#webdev
Long article (478 words) — no AI summary yet.
Reading 0:00
15s threshold

Disclosure: I make WaQueue at Murabyte, which is mentioned at the end.

Two tablets at a clinic door, two people tap "take a number" at the same moment. If both requests read "last ticket = 41" and both write 42, you have a duplicate. Here is how to avoid that in PHP and MySQL.

The wrong way

$last = $pdo -> query ( "SELECT MAX(num) FROM tickets WHERE day = CURDATE()" ) -> fetchColumn ( ) ; $next = $last + 1 ; $pdo -> prepare ( "INSERT INTO tickets (day, num) VALUES (CURDATE(), ?)" ) -> execute ( [ $next ] ) ;

Enter fullscreen mode

Exit fullscreen mode

Between the SELECT and the INSERT, another request can run. Both get the same $next .

The fix: a transaction and a lock

$pdo -> beginTransaction ( ) ; $row = $pdo -> prepare ( "SELECT last_num FROM counters WHERE service_id = ?…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.