0

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

timia2109
  • 732
  • 1
  • 5
  • 11
  • 1
    Tim, [this](https://stackoverflow.com/q/25335137/8469069) is exactly what you need to solve this. Depending on your concurrency, it may be overkill, however it's nice that you worry about this. Good luck! – ishegg Aug 20 '17 at 17:14

1 Answers1

1

If checking of $canBook is executed right after your validation of free slots it should be pretty enough for regular websites.

If there is a possibility of concurrent requests (what is the expected number of active users? how many requests will be for one course in one second?) you can lock your record before checking. Lets say, add a flag in the database and proceed with validation and record updating only if there is no flag. If there is a flag the script will go sleep for a second and check again after that time. The main thread will remove flag after saving course and will transfer control to other threads in this way.

dmkov
  • 334
  • 2
  • 11