I have a form where a user can select a holiday “destination” and a “departure date”.
In addition the user can choose between 3 options.
Search exact date
+/- 3 days
+/- 2 days
+/- 1 days
… etc
The “departure date” is being converted into Unix Timestamp.
What I’m wanting is to is add/subtract (x days) from the departure date so that it creates a date range to search in.
This is what I have so far.
; // ts_todays_date = timestamp of todays date
; //
SELECT DestinationName, UNIX_TIMESTAMP(DepartureDate) as uts_DepDate FROM `holiday_offers` WHERE
UNIX_TIMESTAMP(DepartureDate) = "$ts_todays_date" AND LCASE(`DestinationName`) ="$somelocation"
ORDER BY uts_DepDate DESC
At the moment I can do the exact date, but I am not sure how to go about making MySQL add or subtract days from this search, or create a date range based upon what the user selected.
you could do that, but be careful, if you apply a function to a table column, this usually results in an index scan, or, worse, a table scan (i.e. very poor performance)
the best strategy is to use something like this –
WHERE datecol BETWEEN [I]somevalue1[/I] AND [I]somevalue2[/I]
or, if you are using datetime values (not date values), then this –
WHERE datetimecol >= [I]somevalue1[/I]
AND datetimecol < [I]somevalue2[/I]
in order to come up with somevalue1 and somevalue2, yes, you could use date functions here
for example, find all transactions for yesterday where the transactions have datetime values –
WHERE datetimecol >= DATE_SUB(CURRENT_DATE, INTERVAL 1 DAY)
AND datetimecol < CURRENT_DATE
i will agree that some people think that the unix epoch integer is better (php programmers mainly, and please don’t shoot me, but that’s my impression)
I’ve changed the fields in the database to datetime, and the query;
SELECT *
FROM `offers`
WHERE
DepartureDate >= DATE_SUB( "2009-05-09 00:00:00", INTERVAL 7
DAY )
AND DepartureDate < DATE_SUB( "2009-05-09 00:00:00", INTERVAL -7
DAY )
ORDER BY `DepartureDate` ASC
This seems to be outputting something (I’ve tried it for +/- 30 days) but what I don’t understand is why the INTERVAL -7 DAY has to appear after the INTERVAL 7 DAY.
It just looks odd as I’m wanting it to be searching a period BEFORE/AFTER the date submitted.
I’m doing some tests to see if indeed the data is outputting correctly.