I need to compare 2 dates type "TEXT". My question is, I have date that is exist in the database, and the other date is not existing. How to make query that compare 2 dates type "TEXT", first date is exist, and 2nd date is not. Here is my example data in database 2017 and 2016
My Query is SELECT * FROM oec2 WHERE oec_month BETWEEN '$oec_month1' AND '$oec_month2'
Note: the $oec_month1 (date type TEXT) is exist in db, but the $oec_month2 is not exist.
If I used that query it give me the result of 2017 and 2016
$db = new ezSQL_mysqli(db_user,db_password,db_name,db_host);
$field='date';
$sort='ASC';
if (isset($_GET['search'])){
$branch_id = $db->escape((int)($_GET['branch_id']));
$branch_region = $_GET['branch_region'];
$oec_month1 = $_GET['oec_month1'];
$oec_month2 = $_GET['oec_month2'];
if(isset($_GET['sorting'])){
if($_GET['sorting']=='ASC'){$sort='DESC';$dir="down";}
else {$sort='ASC';$dir="up";}
}
if ($_GET['field']=='result'){$field="result";}
else if ($_GET['field']=='oecgrade'){$field="oecgrade";}
else if ($_GET['field']=='risk'){$field="risk";}
if (!empty($oec_month1)) {
if (!empty($oec_month2)){$searchquery .= " AND (oec_month BETWEEN '$oec_month1' AND '$oec_month2')";}
else {$searchquery .= " AND oec_month >= '$oec_month1'";}
} else if (!empty($oec_month2)){$searchquery .= " AND oec_month <= '$oec_month2'";}
if (!empty($branch_id)) {$searchquery .= " AND (branch_id = '$branch_id')";}
if (!empty($branch_region)) {$searchquery .= " AND (branch_region = '$branch_region')";}
$searchquery .= (" order by $field $sort;");
$site_oec = $db->get_results("SELECT * FROM oec2 WHERE 1=1 $searchquery");
$num = $db->num_rows;
The final output should be the only data in 2017 because the user pick dates between "01/2017" and "02/2017", but it gives me the result of 2016. FYI: The date "02/2017" is not exist.
You can use STR_TO_DATE()
to convert TEXT into appropriate supported date format, then it would be possible to compare values between date.
Example:
If $oec_month1
and $oec_month1
contains date format as:
$oec_month1 = "01/2017";
$oec_month2 = "01/2017";
Then, it may be something like this example:
SELECT * FROM oec2 WHERE oec_month >= STR_TO_DATE($oec_month1, '%m/%Y') AND oec_month <= STR_TO_DATE($oec_month2, '%m/%Y')
For further information about date format please see the link below: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format