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]);
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 = ? AND day = CURDATE() FOR UPDATE");
$row->execute([$serviceId]);
$last = $row->fetchColumn();
if ($last === false) {
$pdo->prepare("INSERT INTO counters (service_id, day, last_num) VALUES (?, CURDATE(), 0)")->execute([$serviceId]);
$last = 0;
}
$next = $last + 1;
$pdo->prepare("UPDATE counters SET last_num = ? WHERE service_id = ? AND day = CURDATE()")->execute([$next, $serviceId]);
$pdo->prepare("INSERT INTO tickets (service_id, day, num) VALUES (?, CURDATE(), ?)")->execute([$serviceId, $next]);
$pdo->commit();
FOR UPDATE makes the second request wait until the first commits, so it reads 42 and writes 43.
Add a safety net
Put a unique key on (service_id, day, num). If your logic ever slips, the database refuses the duplicate.
ALTER TABLE tickets ADD UNIQUE KEY uniq_ticket (service_id, day, num);
Prefixes and daily reset
Give each service its own prefix and format the number on display (A-001, B-001). Because the counter row is per service and per day, numbers restart every day with no cleanup job. The same idea applies to "call next": lock the row you are about to call so two counters cannot call the same ticket.
A ready-made version
WaQueue is a self-hosted PHP/MySQL walk-in queue system I make at Murabyte. It uses database locks for ticket numbering and calling, with a kiosk page, live ticket page, waiting-room display board and a one-tap WhatsApp turn alert that staff send themselves. Not an appointment scheduler, no automatic WhatsApp sending, hosting not included. Regular license $29: https://murabyte.gumroad.com/l/waqueue-arabic-queue-management
php #mysql #webdev #database #murabyte
Written with AI assistance and reviewed by Murabyte.
Top comments (0)