Home > Software design >  Scheduling of available and unavailable rooms - PHP/Mysql
Scheduling of available and unavailable rooms - PHP/Mysql

Time:12-06

I have the following question, how can I prevent a room from being scheduled if the time is already registered in the database?

Example:

Room 1 - check-in 12/20/2022 1:00 pm, check-out 12/20/2022 3:00 pm.

I need this 2 hour break not to be available for scheduling.

I have a table 'scheduling' with the following columns: id, startDate (DATE), startTime (TIME), endDate (DATE), endTime (TIME).

I can't create any logic to block this time interval, and I'm also not sure if this structure is correct in the database...

CodePudding user response:

To prevent a room from being scheduled during a specific time interval, you can use a combination of a SELECT query and a conditional statement in your PHP code.

First, you can use a SELECT query to check if there are any existing records in the 'scheduling' table with the desired start and end dates and times. For example:

SELECT * FROM scheduling WHERE startDate = '12/20/2022' AND startTime = '1:00 pm' AND endDate = '12/20/2022' AND endTime = '3:00 pm';

If this query returns any records, it means that the room is already scheduled during the desired time interval and you can prevent it from being scheduled again by returning an error message or redirecting the user to a different page.

If the query returns no records, it means that the room is available for scheduling during the desired time interval and you can proceed with adding the new record to the 'scheduling' table.

One thing to keep in mind is that you may want to consider using the DATETIME data type for the startDate and endDate columns instead of DATE and TIME. This will allow you to store the date and time as a single value, which can make it easier to compare and check for overlapping time intervals.

For example, you could use a query like this to check for availability:

SELECT * FROM scheduling WHERE startDateTime >= '2022-12-20 13:00:00' AND endDateTime <= '2022-12-20 15:00:00';

This query will return any records where the startDateTime is later than

CodePudding user response:

The only thing that I would add to Sebastian's general comment is that you should use SQL "Transactions" in code such as this.

A "transaction" is a block of SQL statements starting with BEGIN TRANSACTION. From that point on, from everyone else's point-of-view, either "all of the changes will happen at once" when you COMMIT, or "none of them will" if you ROLLBACK. You can specify "isolation levels" to be sure that no so-called "race conditions" occur between multiple users who might be trying to reserve the same room at the same block of time in exactly the same instant. And may I please now refer you to other Internet tutorials if you want to know more.

Here's another SO thread to (for example) look at:

Database race conditions

Also look at the verb, LOCK TABLE.

  • Related