Click to See Complete Forum and Search --> : Date Issue
gaurav_095
01-23-2007, 05:20 AM
hello,
i am having a search page in which i am giving 2 fields for selecting a date (via a calendar),
Let make them from_date AND to_date.
i am having a table in which Lesson_date field is there.
i want to search in such a way that if the user is searching for both the dats ie from-till some date , then only those results should be shown which fall under those (i mean BETWEEN ) those dates.
And if the user is selecting only FROM_DATE then the result should include >= date.
thanks 4 readingg patiently...
-gaurav.
bokeh
01-23-2007, 05:32 AM
Something like this:<?php
$query = 'SELECT * FROM `tablename`';
if(!empty($_POST['from_date']))
{
$query .= ' WHERE `from_date` >= '.$_POST['from_date'];
if(!empty($_POST['to_date']))
{
$query .= ' AND `to_date` <= '.$_POST['to_date'];
}
}
?>
bathurst_guy
01-23-2007, 05:32 AM
etc...
$sql = "SELECT * FROM `table` WHERE `from_date` >= $fromdate";
if(isset($todate)){
$sql .= " AND `to_date` <= $todate";
}
$run = mysql_query($sql);
etc...
gaurav_095
01-23-2007, 05:41 AM
thanks, bokey as weell as to bathurst_guy .
actually, it was as simple as that , but i dunno what happened to me that i thought that there is some KEYWORDS in mysql smthng like 'BETWEEN' which can be used here for comparing dates.
but ,thats ok............
thanks once again to both of u guys .........
-gaurav
NightShift58
01-23-2007, 11:32 AM
I would use BETWEEN/AND where possible:<?php
$query = 'SELECT * FROM `tablename`';
if(!empty($_POST['from_date'])) {
if (empty($_POST['to_date'])) {
$query .= " WHERE `Lesson_date` >= '" . $_POST['from_date'] . "'";
} else {
$query .= " WHERE `Lesson_date` ";
$query .= " BETWEEN '" . $_POST['from_date'] . "'" ;
$query .= " AND '" . $_POST['to_date'] . "'");
}
}
?>If the table is large and performance is an issue, better would be:<?php
$query = 'SELECT * FROM `tablename`';
if(!empty($_POST['from_date'])) {
if (empty($_POST['to_date'])) {
$query .= " WHERE `Lesson_date` >= CAST('" . $_POST['from_date'] . "' as DATE)";
} else {
$query .= " WHERE `Lesson_date` ";
$query .= " BETWEEN CAST('" . $_POST['from_date'] . "' as DATE) ";
$query .= " AND CAST('" . $_POST['to_date'] . "' as DATE) ";
}
}
?>