I am writing a page for a friend where people can book courses. All courses have limited slots.
On a PHP page I will get the free slots of the course (from mysql), check if there is enough space for the booking and then push the data to mysql.
The bookings are saved in a session, when the user fills in information and confirms that booking then this code should be executed which validates and saves all of this to the database.
What happens when there are two requests at the same time? How can I guarantee that the free slots stay free until I push the data to mysql?
I would check it this way
<?php
$canBook = true;
foreach ($_SESSION["booking"]->courseList as $booking) { //For all courses in the session
if ($booking->getCourse()->getFreeSlots() < $booking->slots) { //Check if there are enough slots
$canBook = false;
break; //Not enough free space. Cancel
}
}
if ($canBook) {
//Is the data still vaild? (Think about other requests)
$_SESSION["booking"]->save(); //Add booking to the database and reserve the slots
}
else
showError(); //Show the user an error
?>
Could this be a problem or does this never happen? Or is there a better way to solve that?
Thank you,
Tim