I am writing a query which should only return data for the current day and want to use end time and start time.
Something like this.
$endtime = date ("Y-m-d H:i:s");
$starttime = date ("Y-m-d H:i:s") - 1; // Not working..
$sql = "select * from tbl_order where transdate between $starttime and $endtime";
Can you please help?
RJ
Not 100% sure what you try to achieve, but if you want to get the orders from the past 24 hours (note: not the last day), this will do:
$endtime = date ("Y-m-d H:i:s");
$starttime = date ("Y-m-d H:i:s", (time() - (60*60*24)));
Although I would say it is neater to do this with pure SQL.
The between
keyword operates on date values, not on strings.
<?php
$jan = '2014-01';
$feb = '2014-02';
$sql = "select record_ts from table where date(record_ts)
between str_to_date('$jan', '%Y-%m')
and str_to_date('$feb', '%Y-%m');
";
?>
Notice that I have to convert record_ts to a (MySQL) date because the column is defined as a time stamp, I also have to convert the date-strings.
Carl Maskham, your comment may be valid for recent versions of MySQL.
mysql> select record_ts from table where date(record_ts)
between '2014-01'
and '2014-02' ;
Empty set, 2 warnings (0.01 sec)
mysql> select record_ts from table where date(record_ts)
between str_to_date('2014-01', '%Y-%m')
and str_to_date('2014-02', '%Y-%m');
(...)
1119 rows in set (0.01 sec)
$ mysql --version
mysql Ver 14.14 Distrib 5.1.70, for pc-linux-gnu (x86_64) using readline 5.1
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.