I am writing a hotel booking system. after lots of studying (including stack overflow) i wrote this sql to find out free rooms:
SELECT
*
FROM room
WHERE
room
The problem you're having is that your query is not sufficiently robust. When you break down the problem, what you have is this:
If the range defined by $check_in
and $check_out
overlaps the range defined by checkin
and checkout
in any way, then the room is booked. Otherwise, it is free.
This means that:
$check_in
>= checkin
and $check_in
<= checkout
, the room is BOOKED$check_out
>= checkin
and $check_out
<= checkout
, the room is BOOKED$check_in
<= checkin
and $check_out
>= checkout
, the room is BOOKEDSo, you need to represent both of these scenarios in your subquery in order to get the information you're looking for.
Also, you will hopefully be using datetime
for your comparisons and not just time
, otherwise you will have side effects.
EDIT: SQL Query
(Keep in mind that there is more than one way to skin a cat, so to speak. I'm just providing an example that keeps with what you already have as much as possible. Once again, I'm also assuming that checkin
, checkout
, $check_in
, and $check_out
will all resolve to datetime
types)
SELECT *
FROM room
WHERE room_id NOT IN
(SELECT room_id
FROM bookings
WHERE
(checkin <= '$check_in' AND checkout >= '$check_in') OR
(checkin <= '$check_out' AND checkout >= '$check_out') OR
(checkin >= '$check_in' AND checkout <= '$check_out'))