Hotel room booking/reservation - php

I'm working on a reservation/booking system for a small hotel. I'm pretty good with PHP but not so good with SQL... I made a form where you enter your information, number of rooms and select arrival date and check-out date using a calendar.
Now everything went good until I got to the point where you have to check which rooms are available and it's giving me a headache. There are 10 rooms you can book.
I currently have one table in MySQL storing the information, dates, booking-ID and room-ID/number.
How would you make the SQL for checking which rooms that are available and not?
Should it look something like
"SELECT * FROM bookings WHERE checkinDate >= '$formCheckin'
AND checkoutDate <= '$formCheckout' "
and then get the roomID and count them?
Any help is very appreciated!

If you want to know if a room is available during a period, then the logic looks like:
SELECT r.*
FROM rooms r
WHERE NOT EXISTS (SELECT 1
FROM bookings b
WHERE b.roomid = r.roomid AND
b.checkinDate <= $formCheckOut AND
b.checkoutDate >= '$formCheckIn
);
I'm not sure if the equality comparison is needed for both of these. The logic is that a room is available if there are no bookings that start before the checkout date and that end after the check in date.
However, for ten rooms, I might suggest that you just keep a table of each room by day, say for the next ten years (add another year once per year). Such a table isn't very big and it is probably easier to understand how to use it. Plus, you can handle things like a couple reserve the room for a week, but only one person is in the room for the first 3 days.

Related

Hotel room availability

I want to check if any other room is available between check in and check out date. If a single day also booked between the submitted date, that room should not be included. Image shows the booked room. If I enter check in date like 2016-05-16 and check out date like 2016-05-21 then total no of booked room should be answered as 9 for hotel id=1
My code is like-
='$i' and end_date='$i') and hotel_id='1'");
$rows=mysql_fetch_row($sel);
$count[]=$rows[0];
echo ''.$i.$rows[0];
}
foreach($count as $c)
{
echo "---".$c;
}
?>
I don't know the SQL you are using so I will do a general approach trying to help you.
What you need there is the SQL BETWEEN Operator, in partitucular its negative, NOT BETWEEN in order to check if the room is empty.
The logic would be, I want to query every empty room, this means that today's date should not be between check in and check out dates.
Your query should look something like:
SELECT * FROM TableName
WHERE NOW() NOT BETWEEN start_date AND end_date;
As a recommendation I suggest you to read How to Ask to get more accurate help in the future.
Hope this helped you :)

How do I use price data in one table for a calculation that is stored in another table?

I'm still leanring PHP/MySQL but have learned quite a bit thanks to codies on StackOverflow. I'm trying to setup a sort of room reservations system using two tables:
SETUP:
Room price table: Has, prices for a type room a client may want to rent as well as the dates (day of week) they wish to use it. Pricing varies based on day of the week and per room.
I've setup a different table for each room type as each room type carries different pricing for each day of the week. So, There is an Alpha room table, Bravo room, etc. Within Alpha table are headers for the days of the week with pricing pre-entered into the rows.
Client info table: Has the name, address, date of room use, etc data for the specific client.
EXAMPLE:
Alpha-room price table:
Sun = $100; Mon = $200; Tue=$300 and so on.
Bravo-room price table:
Sun = $100; Mon = $200; Tue=$300 and so on.
Client data table:
ClientName; date-of-room-use; address; day_subtotal; grand_total.
QUESTION:
I'm trying to find PHP code that will:
look at the date of room use in the client data table,
look up the associated cost for that date in the specific room pricing table,
record that unit cost in the day subtotal of the client data table
and sum a grand total in the grand total row of the client data
table (assuming the room may be used more than one day by the
customer).
I know there's something to do with join but I'm finding it difficult to grasp the concept and, if someone can demonstrate using this example, I think I will have a better understanding of how to work this sort of transaction.
Thank you ALL in advance for your suggestions or alternatvie approaches.
First, you should separate your database slightly, you should have four tables. rooms, prices, clients and bookings. Setup somewhat like this...
rooms should have the following fields: id, name and description.
prices should have the following fields: id, price, room_id and day.
clients should have the following fields: id and whatever else you want to store on the user, such as first and last names, phone number or whatever.
bookings should have the following fields: id, client_id, room_id, started_at and ended_at. Preferably the started_at and ended_at fields will be an int, filled with PHP's time() method.
You can add any extra fields you want/need to the tables.
With the tables separated out like this, you will be able to properly query the database. So to answer your questions...
look at the date of room in use...
You can now query to see if a room is in use on a specific date by doing the following...
<?php
$selectedDate= mktime(); // Create a UNIX timestamp based on the day the user selected.
$query = "SELECT r.name, r.description
FROM rooms r, bookings b
WHERE b.room_id = r.id
AND b.started_at < $selectedDate
OR b.ended_at > $selectedDate";
$result = $pdo->query($query);
?>
Look up cost for that date
<?php
$selectedDate = mktime() // Create a UNIX timestamp based on the day the user selected
$dayOfWeek = Date('N', $selectedDate); // This will give the numerical day of the week.
$query = "SELECT price
FROM prices
WHERE room_id = $roomId
AND day = $dayOfWeek";
$result = $pdo->query($query);
?>
Record that unit cost in the client table
Doing this is just silly on account of already having the information in another table. Never recreate the same information in a database. If you are, you have built your database incorrectly.
Grand total in the customer table
Again, silly... don't recreate data...
Though, to find that information out, you would first need to do a query on the bookings table, and see the start and end date for which the user will be occupying the room.
Do a calculation on how long the client will be in the room for, (ended_at - started_at) / 86400, (86400 is the number of seconds in a day) that will give the number of days the client is in the room for.
Now that you know which days, and how long the client will be in the room, you can dynamically create a sql call to select the days of the week you need, remember Date('N', $timeStamp) will give you the numerical day of the week for a given timestamp.
Then it is just a matter of doing simple addition.
I have given you the basics here, You can modify the query from answer one to show you if a room is available to be booked within the time frame the user asked for.
I hope that covers everything you asked about...

Reservation system dates

I have problem thinking this trough with PHP & Mysql. I have read How to implement check availability in hotel reservation system and some more but they seem different.
I have to make a reservation system on which a converence room can be booked for 6hours minimal, so when a user make a reservation on a date e.g 24/04/2012 he then selects the start time of the rental (00:00-06:00, 06:00-12:00, 12:00-18:00,18:00-24:00). And the total number of hours(6,12,18 etc..) the user wants to rent the room.
The date is stored as a integer(timestamp).
I have two problems with this; I donĀ“t know how to receive all possible days of a month on which the room is still up for reservation and how to check if a new reservation is possible.
I know how to calculate the start date and end date on the users input but I cant find the correct mysql query or php check for availability.
It's probably really simple but somehow because the end date is always variable I just cant find the answer.
Thanks in advance guys!
EDIT Table structure: reservations
id int(11)
user_id int(11)
reservation_name varchar(255)
start_date int(11)
end_date int(11)
I believe reservations is the only one relevant
You'll find it's pretty difficult to generate a list of available days in MySQL. I recommend instead that you select an ordered list of booked days within your desired month, then loop over all days of that month in PHP skipping the day if it matches the next booked day from your MySQL query. The answer to this question will help you to build the dates over which you want to loop in PHP. In pseudocode:
$booked_days = sql(select all booked days in month order by day);
for each $day in month {
if $day != current($booked_days) {
// $day is not booked
} else advance_next($booked_days);
}
To check if a new reservation is possible, you might want to have a look at my answer to a very similar question earlier today.
This brilliant simple MySQL query must do the trick:
Checking for overlapping car reservations
This solution is only for "dates" but You can simply aggregate it with additional "hours"

Is it good or bad practise to alter start dates in a database to the next occurrence of an event?

I am trying to create an event calendar which whilst initially quite small could turn out to be quite large. To that end, when trying to future proof it as much as possible, all events that occur in the past will be deleted from the database. However, is it bad practise to alter the start date of recurring events once they have happened to indicate when the next event will start? This makes it easier to perform search queries because theoretically no events will start more than say a week in the past, depending on how often the database is updated.
Is there a better way to do this?
My current intention is to have a table listing the event details along with a column for whether it is a yearly, monthly, weekly or daily recurrence. When somebody then searches for events between 2 dates, I simply look at each row and check if (EVENT START <= SEARCH FINISH && EVENT FINISH >= SEARCH START). This then gets all the possible events, and the recurring ones then need to be checked to see if they occur during the time period given. This is where I come a little unstuck, as to how to achieve this specifically. My thoughts are as follows:
Yearly: if EVENT START + 1 YEAR <= SEARCH FINISH || EVENT FINISH + 1 Year >= SEARCH START; repeat for +2 YEARS etc until EVENT START + NO YEARS > SEARCH FINISH.
Monthly: As above but + 1 month each time.
Weekly: As above but EVENT START and EVENT FINISH will be plus 7 DAYS BETWEEN RECURRENCE each iteration until EVENT START + 7 DAYS REPEATED > SEARCH FINISH.
Daily: As above but NO OF DAYS DIFFERENCE instead of 7 days for a week. This could be used to specify things like every 14 days (fortnight), every 10 days. Even every week could use this method.
However, when I think about the query that would have to be built to achieve this, I cannot help think that it will be very cumbersome and probably slow. Is there a better way to achieve the results I want? I have still not found a way to do things like occurs on the first Monday of a month or the last Friday of a month, or the second Saturday of April each year. Are these latter options even possible?
-- Edit: added below:
It might help a bit if I explain a bit more about what I am creating. That way guidance can be given with respect to that.
I am creating a website which allows organisations to add events, whether they are a one-off or recurring (daily, weekly, monthly, first Tuesday of a month etc.). The user of the site will then be able to search for events within a chosen distance (arbitrary 10, 25, 50, 100miles, all of country) on a set date or between 2 given dates which could be from 1 day apart up to a couple of years apart (obviously events that far into the future will be minimal or non-existant depending on the dates used).
The EVENTS table itself currently holds a lot of information about the event, such as location, cost, age group etc. Would it be better to have this in a separate table which is looked up once it has been determined if the event is within the specified search parameters? Clearly not all of this information is needed until the detailed page view, maybe just a name, location, cost and brief description.
I appreciate there are many ways to skin a cat but I am unsure how to skin this one. The biggest thing I am struggling with is how to structure my data so that a query will know if the recursion is within the specified date. Also, given that the mathematics to calculate distance between 2 lat/longs is relatively complex, I need to be able to build this calculation into my query, otherwise I will be doing the calculation in PHP anyway. Granted, there will be less results to process this way, but it still needs to be done.
Any further advice is greatly appreciated.
Creating events for each recurrence is unnecessary. It is much better to store the details that define how the event recurs. This question has been answered many times on SO.
One way to do this is to use a structure like this -
tblEvent
--------
id
name
description
date
tblEventRecurring
-----------------
event_id
date_part
end_date
Then you could use a query like this to retrieve events -
SELECT *
FROM `tblEvent`
LEFT JOIN `tblEventRecurring`
ON `tblEvent`.`id` = `tblEventRecurring`.`event_id`
WHERE (`tblEvent`.`date` = CURRENT_DATE AND `tblEventRecurring`.`event_id` IS NULL)
OR (
CURRENT_DATE BETWEEN `tblEvent`.`date` AND `tblEventRecurring`.`end_date`
AND (
(`tblEventRecurring`.`date_part` = 'D') OR
(`tblEventRecurring`.`date_part` = 'W' AND DAYOFWEEK(`tblEvent`.`date`) = DAYOFWEEK(CURRENT_DATE)) OR
(`tblEventRecurring`.`date_part` = 'M' AND DAYOFMONTH(`tblEvent`.`date`) = DAYOFMONTH(CURRENT_DATE))
)
)
UPDATE Added the following example of returning events for a given date range.
When returning dates for a given date range you can join the above query to a table representing the date range -
SET #start_date = '2012-03-26';
SET #end_date = '2012-04-01';
SELECT *
FROM (
SELECT #start_date + INTERVAL num DAY AS `date`
FROM dummy
WHERE num < (DATEDIFF(#end_date, #start_date) + 1)
) AS `date_list`
INNER JOIN (
SELECT `tblEvent`.`id`, `tblEvent`.`date`, `tblEvent`.`name`, `tblEventRecurring`.`date_part`, `tblEventRecurring`.`end_date`
FROM `tblEvent`
LEFT JOIN `tblEventRecurring`
ON `tblEvent`.`id` = `tblEventRecurring`.`event_id`
WHERE `tblEvent`.`date` BETWEEN #start_date AND #end_date
OR (`tblEvent`.`date` < #end_date AND `tblEventRecurring`.`end_date` > #start_date)
) AS `events`
ON `events`.`date` = `date_list`.`date`
OR (
`date_list`.`date` BETWEEN `events`.`date` AND `events`.`end_date`
AND (
(`events`.`date_part` = 'D') OR
(`events`.`date_part` = 'W' AND DAYOFWEEK(`events`.`date`) = DAYOFWEEK(`date_list`.`date`)) OR
(`events`.`date_part` = 'M' AND DAYOFMONTH(`events`.`date`) = DAYOFMONTH(`date_list`.`date`))
)
)
WHERE `date_list`.`date` BETWEEN #start_date AND #end_date
ORDER BY `date_list`.`date`;
You can replace the SQL variables with PHP vars if you would prefer. To display days without any events you can change the INNER JOIN between the two derived tables, date_list and events, to a LEFT JOIN.
The table dummy consists of a single column with numbers from 0 to whatever you anticipate needing. This example creates the dummy table with enough data to cover one month. You could easily populate it using an INSERT... SELECT... on the AI PK of another table -
CREATE TABLE `dummy` (
`num` SMALLINT UNSIGNED NOT NULL PRIMARY KEY
);
INSERT INTO `dummy` VALUES
(00), (01), (02), (03), (04), (05), (06), (07), (08), (09),
(10), (11), (12), (13), (14), (15), (16), (17), (18), (19),
(20), (21), (22), (23), (24), (25), (26), (27), (28), (29),
(30), (31);
Break it up
Have one table for vents that haven't happened yet with a reccurring event ID. So you can just poke one offs in there with recurring veent id of null. Get rid /archive past ones etc.
Have another for the data about recurring events.
When an event marked as recurring happens, go back to recurring table, check to see if it's enabled (you might want to add a range to them ie do this every wek for three months), and if all is okay, add a new record for the next time it occurs.
One way to do it anyway, and it gets rid of the problem of using event start for two different things which is why your code is getting complicated.
If you want future jobs from this. ie everything needed to do in the next month.
The it would be a union query. One to get all teh "current jobs", unioned with one to get all the jobs that will recur in the next month.
Can't stress this enough, get the data design right the code "just happens". If you data is messed up as in one field "start date" serving two different needs, then every time you go near it, you have to deal with that dual use. Forget it once and you get anything from a painful mess to a disaster.
Adding a Recurring_Start_Date column would be better than your current plan, wouldn't it. You wouldn't be asking this question, beacseu your data would fit your needs.
I assume you'll be searching through events much more frequently than you will be creating new ones. During event creation, I would create records for each occurrence of the event up to so reasonable amount of time (maybe for the next year or two).
It would also make things like "The third thursday of each month" a little easier. If you tried to do any of the calculations in a query it would be difficult and probably slow.

Booking query does not consider arrival and departure day

I have been searching for an answer to this dilemma but found nothing. I was hoping you could help to find out what I am doing wrong.
I have a mysql query that selects only apartmens available as follow:
SELECT *
FROM apartments
WHERE apartment_ID NOT IN (SELECT apartment_ID
FROM bookings
WHERE startDate <= '$endingdate'
AND endDate >= '$startingdate')
The problem is that this query is not considering that i.e. departure day is an half day and it is available.
To explain better:
if table "booking" has a booking ending on 16-01-2011 and the search is from the 16-01-2011. The apartment should be available because that is an "half" day (the day of departure). The query seems to not consider this and does not show the apartment.
Please could you help?
Francesco
I'm not that familiar with MySQL data types , but are you sure that startDate and endDate are not stored with a time part as well. If that's the case then "16-01-2011 16:25" would not be less than or equal to "16-01-2011".
Take out the = signs from your sub query, or at least the last one if a place vacated on a date is always available on that date. That should check for apartments being vacated on the requested date. Also make sure that your data is escaped.
If availabilty depends on time then you will need to change your date fields to datetimes.

Categories