r/PHPhelp • • Oct 09 '17

Checking for availability between dates

So basically I am to make a reservation system for a resort. I have already made a database: https://imgur.com/f9aLyFZ. I really need to know how to check if dates are available when making a reservation.

So far I did this: $sql = "SELECT * FROM room_type_tbl

    INNER JOIN room_tbl ON room_type_tbl.room_type_id=room_tbl.room_type_id

    WHERE room_type_tbl.room_capacity='$roomcap' && ('$datein'>booking_tbl.checkin_date && '$dateout'<booking_tbl.checkoutdate)
";

if ($conn->query($sql) === TRUE) {
    //echo "Table MyGuests created successfully";
} else {
  echo "Error creating table: " . $conn->error;
}

It's not working and I'm about to go mad. Please help me.

8 Upvotes

7 comments sorted by

View all comments

1

u/fz-09 Oct 10 '17

Are you trying to obtain all rooms with a given room capacity that are available on a given day?

SELECT r.* FROM room_tbl r
LEFT JOIN booking_tbl b
    ON b.table_id = r.table_id
    AND ? BETWEEN r.checkin_date AND r.checkout_date
JOIN room_type_tbl rt
    ON r.room_type_id = rt.room_type_id
WHERE rt.room_capacity = ?
    AND b.id IS NULL

1

u/dutchydownunder Oct 11 '17

^ Would need to check for start and end date the new guest wants to stay, not just a single date.

expected stay = es
already booked = ab

ab.endDate => es.startDate AND ab.startDate <= es.endDate

Then we left join room_tbl and booking_tbl on room_id on the above criteria and where booking_tbl.room_id is null

SELECT room_tbl.room_id
FROM `room_tbl` 'room'
LEFT JOIN `booking_tbl` 'booking'
    ON room.room_id = booking.room_id AND \es.startDate\ => booking.checkoutdate AND \es.endDate\ <= booking.checkin_date
WHERE booking.room_id is null

Should work, not sure, sitting in boring meeting browsing reddit ;-) Now write out all date range scenarios you can think of and start testing.

Some reservations I have about this: I would never use the actual rooms for bookings, rather have a free room count per type, and bookings per room type. This allows you to have a numerical buffer, for let's say taking rooms out of rotation for maintenance. Hotels normally assign the room number when you check in based on what is available. This also allows hotel staff to make crucial decisions, rather than a specific room being overbooked, a room type becomes overbooked instead. Personal preference perhaps.