I'm designing a car booking system and I'm trying to write a query that will check whether a car is available. What I want the query to do in english is to check that the start hire and end hire selected which are stored in variables $mysql_startdate and $mysql_enddate do not overlap with any existing bookings.
I have checked that the variables in the query have the value that they should have so I'm guessing there is a problem with my syntax, most likely the last part.
Format of datetime variables:
$mysql_startdate = 2012-03-22 00:00
$mysql_enddate = 2012-03-23 00:00
I am getting no errors from mysql_error, the problem is that no results are displayed even if a car that is available is requested.
$query = "SELECT c.*,b.startHire,b.endHire FROM cars c JOIN bookings b WHERE c.currentBranch = '$pickUpLocation' AND NOT (b.startHire > '$mysql_enddate' OR b.endHire < '$mysql_startdate')";
The startHire and endHire fields in the database are set to datetime and have the format - 2012-03-02 00:00:00 etc.
Can you help me to identify the problem and amend the sql query?
Let me know if you need any further code/information.
Thank you!
Try that:
SELECT c.*, b.startHire, b.endHire
FROM cars c JOIN bookings b
WHERE c.currentBranch = '$pickUpLocation'
AND NOT b.startHire between '$mysql_startdate' and '$mysql_enddate'
and not b.endHire between '$mysql_startdate' and '$mysql_enddate'
Related
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 :)
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.
Say I have a table like this :
Say I want to select a column from id = 4 and date=2014/2/14
I must say mysql like this:
$db = new mysqli("localhost",'root','','myDatabase');
$sql = "SELECT * FROM myTable WHERE id=`4`";
$result= $db->query($sql);
while($row = $result->fetch_object()){
$time = $row->"2014/2/14";
echo $time;
}
And this will result like this:
9-10AM
So far it's OK with no problem
But say I want to select 6 coumun after 2014/2/14 too!!
every time I select an id an a date like 2014/2/14 , I want to show 6 day after 2014/2/14
I mean I expect result to be like this(continuing my example):
bold
9-10AM
8-10AM
9-10AM
6-7PM
for god sake, please don bit around the bushes
see:
how to do this?
Since a 75K trolling user (who now covered his tracks by deleting all comments) thinks it is wise to first teach you about complicated things like SQL injection and how to prevent this here we go. So better first read through these links you won't learn anything since it expects you to know the basics but we do not seem to care here in this community.
http://www.us-cert.gov/sites/default/files/publications/Practical-SQLi-Identification.pdf
http://www.cc.gatech.edu/fac/Alex.Orso/papers/halfond.viegas.orso.ISSSE06.pdf
http://web.archive.org/web/20070928163708/http://www.ngssoftware.com/papers/advanced_sql_injection.pdf
https://media.blackhat.com/us-13/US-13-Salgado-SQLi-Optimization-and-Obfuscation-Techniques-WP.pdf
While we are learning already about injection it might be wise to know how to optimize your database too since you are talking about large numbers.
http://www.mysqlperformanceblog.com/files/presentations/UC2005-Advanced-MySQL-Performance-Optimization.pdf
And a comprehensive guide to working with date and time since you want to work with date and time.
http://oreilly.com/catalog/mysqlian/chapter/ch06.pdf
(believe me, i would have written all these guides down here for future reference but that would take to much time, so forgive me that i just post the links).
Now you are probably a view years older and know pretty much about MySQL, yet i leave my original answer here for others that might bump into the same problem. You have to look into normalization of your database. Mysql can look for time and dates if they are records inside a table. Not if they are column headers.
name your columns like: ID - date - time
Now you can search for a certain time with BETWEEN like this:
WHERE date BETWEEN (yourdate) AND (yourdate + INTERVAL 7 DAY)
This will result in picking all records from the date you select plus 7 days.
-edit-
As for your comment, name your tables like ID - doctor - date - time
Now if you want to see all doctors availability in the comming week between 9:00 and 12:00 do:
$doctorQuery = mysql_query("SELECT doctor FROM theTable WHERE date BETWEEN (NOW()) AND (NOW() + INTERVAL 7 DAY) AND date TIME 9:00:00 AND 12:00:00");
while ($result = mysql_fetch_assoc($doctorQuery))
{
echo $result['doctor']; //you can output it here already.
$resultarray[] = $result; //or store it for later in a 3 dimensional array.
}
foreach ($resultArray = $singleRow)
{
echo $singleRow['doctor']; //And output it whenever you want.
}
Forgive me, i'm little rusty and this all is not tested. But this should sent you in the right direction. Please for your own sake, believe us and do not create collumns with dates as headers. This will cause problems later on, one reason is, in two years from now you would have added 730 columns to your table. Of course you could use the dates from my table to output them as headers on your website to make it humanly readable.
-Another edit-
As for you latest comment you probably need a table structure like this:
table for doctors and there info:
[doctorID]-[doctorName]-[doctorInfo]-[LinkToPicture]
Here you fill in a single row for every doctor you have.
Table for there work times:
[timeID]-[doctorID]-[date]-[workhours]
doctorID is a link key, or foreign key which tells the table to which doctor this row belongs. Here fill in the date and time the doctor works. You can insert as many records as you want for each doctor.
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...
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.