use WHERE CLAUSE for search data from A date until B date

浪尽此生 提交于 2019-12-24 16:27:47

问题


lets say i have two drop down list and one button on my search page:

From
<select id="1stdate">
Until
<select id="2nddate">
<input type="button" id="search">

i want to search data from 1stdate until 2nddate, how to use WHERE CLAUSE for this case? for ex. i want to search data "from 09-2010 until 11-2010". this my query:

SELECT CONCAT( YEAR(Inspection_datetime ),'-',LPAD(MONTH(Inspection_datetime),2,'0'))
FROM `inspection_report`
GROUP BY  CONCAT( MONTH(Inspection_datetime ),YEAR(Inspection_datetime))
ORDER BY  CONCAT( MONTH(Inspection_datetime ),YEAR(Inspection_datetime))  DESC

回答1:


I usually did something like this:

<?php

list($m1, $y1) = explode($_1stdate);
list($m2, $y2) = explode($_2nddate);

$date1 = "$y1-$m1-01";
$date2 = "$y2-$m2-" . date("t", mktime(0,0,0,$m2, 1, $y2));

$sql = "SELECT *
FROM `inspection_report`
WHERE DATE(Inspection_datetime) BETWEEN '$date1' AND '$date2'";

Please note: for simplicity's sake, I don't add form validations.




回答2:


this is what you need:

WHERE Inspection_datetime BETWEEN $1stdate AND $2nddate

so it will result in

SELECT CONCAT( YEAR(Inspection_datetime ),'-',LPAD(MONTH(Inspection_datetime),2,'0'))
FROM `inspection_report` WHERE Inspection_datetime BETWEEN $1stdate AND $2nddate
GROUP BY  CONCAT( MONTH(Inspection_datetime ),YEAR(Inspection_datetime))
ORDER BY  CONCAT( MONTH(Inspection_datetime ),YEAR(Inspection_datetime))  DESC


来源:https://stackoverflow.com/questions/3913110/use-where-clause-for-search-data-from-a-date-until-b-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!