[英]between operator for timestamps in mysql query
I have a form to pick up dates from calender. 我有一个表格,可以从日历中提取日期。 That form will pass start date and end date. 该表格将通过开始日期和结束日期。 My database table stores date in time-stamp format. 我的数据库表以时间戳格式存储日期。 I have to create a query to pick records from database table between start date and end date. 我必须创建一个查询以从开始日期和结束日期之间的数据库表中选择记录。 How can I make a query? 如何查询? I have tried the code below, but which is not working. 我已经尝试了下面的代码,但是没有用。
if(isset($_POST['filter']))
{
$sid=$_POST['sid'];
$start= date("dMY",strtotime($_POST['start']));
$end= date("dMY",strtotime($_POST['end']));
$res=$db->fetchAll("SELECT * FROM `logfile` WHERE `site_id`=".$sid." AND (date('dMY',`timestamp`) BETWEEN $start AND $end)");
}
Any thoughts? 有什么想法吗?
Thanks. 谢谢。
You're forcing PHP and MySQL to do a lot of useless date/time string<->native conversions for no reason. 您强迫PHP和MySQL无缘无故地执行许多无用的日期/时间字符串<->本地转换。
Why not simply have: 为什么不简单地拥有:
$start = strtotime($_POST['start']);
SELECT ... WHERE `timestamp` BETWEEN FROM_UNIXTIME($start) AND ...
As @Matei Mihai said you don't need to convert $_POST['start']
and $_POST['end']
to timestamp format and you must enclose date columns in quotes. 正如@Matei Mihai所说,您不需要将$_POST['start']
和$_POST['end']
为时间戳格式,并且必须将日期列括在引号中。
Also you need to convert date in MySQL compatible format like '2012-08-01'
. 另外,您需要将日期转换为MySQL兼容格式,例如'2012-08-01'
。
"SELECT *
FROM `logfile`
WHERE `site_id`=".$sid." AND
(date('dMY',`timestamp`) BETWEEN '$start' AND '$end')");
if $_POST['start']
and $_POST['end']
are already in timestamp format, just don't change them. 如果$_POST['start']
和$_POST['end']
已经采用时间戳格式,则不要更改它们。 In other case just convert the string in timestamp: 在其他情况下,只需在时间戳记中转换字符串即可:
$start = strtotime($_POST['start']); // where $_POST['start'] might be 2012/08/07
$end = strtotime($_POST['end']);
$res=$db->fetchAll("SELECT * FROM logfile WHERE site_id=".$sid." AND date BETWEEN $start AND $end");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.