Reputation: 696
I have a database where people can book rooms within two certain times, but there may be other people searching for an available room within the same times - or partly in the same time.
Database looks like this:
order | room | user | date (date-format) | from (time) | to (time)
1 123 foo 2013-04-04 12:00:00 17:00:00
The problem comes when another user searches if the room is available from f.ex 13:00 to 18:00, since I only manage to search if the room is available in the exact same time.
The query has to search on specific room at a specific date, and a time aswell. If the room is busy in all, or some of the hours, I'd like to catch this and say to the user that the room is busy.
Any tips? If it's easier to manage through PHP I'd be glad too :-)
Upvotes: 1
Views: 808
Reputation: 4956
An improvement on the answer by @Delphinator
SELECT *
FROM booked
WHERE
room=$room AND
date=$date AND
(
TIME("$start_time") BETWEEN from and to
OR
TIME("$end_time") BETWEEN from and to
);
BETWEEN
does exactly what you would think.
Upvotes: 1
Reputation: 513
Why not solve it using SQL like this (untested):
SELECT *
FROM booked
WHERE
room=$room AND
date=$date AND
(
(
/*
The reservation starts in the requested period
*/
from <= $start_time AND
to > $start_time
) OR (
/*
The reservation ends in the requested period
*/
from < $end_time AND
to >= $end_time
)
);
This query will return all reservations between $start_time
and $end_time
and allows reservations back to back. If you don't want to allow reservations back to back change the <
and >
to <=
and =>
.
Important: Make sure to not just use string interpolation and insert user-supplied input unescaped as it will leave your application vulnerable to SQL-injection attacks.
Upvotes: 2