Here i have a column which is in datetime format.I want to search the table by a given daterange.But the query i wrote is generating an error
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '14:27:12) AND date(2016-06-28 14:27:12) LIMIT 0, 30' at line 1
SELECT * FROM `tele_incoming_call` WHERE DATE(`incoming_call_date`) BETWEEN date(2016-06-27 14:27:12) AND
date(2016-06-28 14:27:12)
i have found that the following sql works for me
SELECT * FROM `tele_incoming_call` WHERE `incoming_call_date` BETWEEN '2016-06-27' AND
'2016-06-28'
Remove date
and quote the times.
SELECT * FROM `tele_incoming_call` WHERE (incoming_call_date BETWEEN '2016-06-27 14:27:12' AND '2016-06-28 14:27:12')
SELECT * FROM `tele_incoming_call` WHERE MONTH(`incoming_call_date`) BETWEEN MONTH(2016-06-27 14:27:12) AND
MONTH(2016-06-28 14:27:12) AND YEAR(`incoming_call_date`) BETWEEN YEAR(2016-06-27 14:27:12) AND
YEAR(2016-06-28 14:27:12) AND DAY(`incoming_call_date`) BETWEEN DAY(2016-06-27 14:27:12) AND
DAY(2016-06-28 14:27:12)
but better is
SELECT * FROM `tele_incoming_call` WHERE `incoming_call_date` BETWEEN '2016-06-27 00:00:00' AND '2016-06-28 23:59:59'
date(2016-06-27 14:27:12)
within MySQL query is wrong.
Update the Query to the following.
$sql_query="SELECT *
FROM `tele_incoming_call`
WHERE DATE(`incoming_call_date`)
BETWEEN ".date('Y-m-d',strtotime('2016-06-27 14:27:12'))." AND
".date('Y-m-d',strtotime('2016-06-28 14:27:12'));
To get the get from String we can use strtotime() which converts the given string to Unix timestamp.
And then we pass that timestamp to date() to get the date in required Y-m-d
format to compare in MySQL.
Update:
You can make use of DATE_FORMAT MySQL function to compare dates only.
So your query will look like this,
$sql_query="SELECT *
FROM `tele_incoming_call`
WHERE DATE(`incoming_call_date`)
BETWEEN DATE(STR_TO_DATE('2016-06-28 14:27:12','%Y-%m-%d %H:%i:%s'),'%Y-%m-%d') AND
DATE(STR_TO_DATE('2016-06-28 14:28:12','%Y-%m-%d %H:%i:%s'),'%Y-%m-%d')";