I have a single mysql table called prices storing dates from and to like so:
id from to price
1 2013-11-25 2014-01-08 55
the user selects a month and a year and i want it to show all results that either are from or to that month so if the user selected either november 2013, december 2013 or january 2014 it would include the above row.
id from to price
2 2013-10-25 2013-11-07 100
and if they selected either october or november 2013 it would show the above row because it starts in october and ends november.
i have tried
SELECT * FROM `prices`
WHERE MONTH(prices.from)<={$_SESSION['month']}
AND MONTH(prices.to)>={$_SESSION['month']}
AND YEAR(prices.to)={$_SESSION['year']}
ORDER BY prices.from ASC
which doesn't work i'm not sure how this can be done
You could use STR_TO_DATE to create a date from the month and year the user selects and then use DATE_FORMAT to put your table's date column in YYYY-MM format and compare both with the YYYY-MM the user inserted.
I'm not fluent in php, but here's an example in sql (you can use any day in the str_to_date, since you will ignore it):
SELECT * FROM `prices`
WHERE DATE_FORMAT(prices.`from`,"%Y-%m") <=
DATE_FORMAT(STR_TO_DATE('01,10,2013','%d,%m,%Y'),"%Y-%m")
AND DATE_FORMAT(prices.`to`,"%Y-%m") >=
DATE_FORMAT(STR_TO_DATE('01,10,2013','%d,%m,%Y'),"%Y-%m")
ORDER BY prices.`from` ASC
Try to use "BETWEEN" instead. example:
SELECT * FROM `prices` WHERE MONTH(`from`) BETWEEN '10' AND '12' AND YEAR(`to`)='2013'
Follow this method:
SELECT * from prices
WHERE str_to_date('{$_SESSION['month']}-{$_SESSION['year']}','%b-%Y') BETWEEN date(prices.from) AND date(prices.to)
You might just want to use the correct format in the str_to_date, currently it converts the following format = Oct-2013
Check this for other formats: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_str-to-date
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.