我的数据库中有一个表,将用户输入存储为开始日期和结束日期,之后我的用户必须选择一个时间范围,并且我必须在表中显示该时间范围内的那些记录?
尝试stritotime();
了许多其他的功能,但不知何故我无法得到正确的结果..
任何可能的解决方案将不胜感激。
谢谢!
可能与:
SELECT count(*) FROM `table`
where
created_at>='2011-03-17 06:42:10' and created_at<='2011-03-17 06:42:50';
或在以下之间使用:
SELECT count(*) FROM `table`
where
created_at between '2011-03-17 06:42:10' and '2011-03-17 06:42:50';
这取决于您要显示的记录,因为我没有看到您的表格和您真正要做的示例,只需更改计数(*)并获取您想要的记录。
编辑:如果用户将选择一个时间范围,那么他们将是变量
那么它会是这样的
SELECT records FROM `table`
where
created_at >= '".$var_start_time."' and ended_at <= '".$var_end_time."';
You can simply do this in your SQL, which is the recommended approach. If you have these start and end times stored in your database table as native DateTime types, for example, you can use your DBMS' Date functions to select the range as a UNIX timestamp (if that's what what you want).
SELECT UNIX_TIMESTAMP(`start_time`), UNIX_TIMESTAMP(`end_time`) FROM `table` WHERE `start_time` > INTERVAL -1 DAY AND `end_time` < NOW();
That's one example (assuming you're using MySQL) where you select all rows in the table where the column start_time
is within the past 24 hours and the end_time
column is up to the current server time.
To get the formatted date and then do the conversion to a UNIX time-stamp in PHP use:
SELECT `start_time`, `end_time` FROM `table` WHERE `start_time` > INTERVAL -1 DAY AND `end_time` < NOW();
and then in PHP you can do:
$result['start_time'] = strtotime($result['start_time']);
$result['end_time'] = strtotime($result['end_time']);
Keep in mind that strtotime expects the formatted date to comply with PHP's date parsing rules found here.
P.S: The function in PHP you're looking for is strtotime not stritotime.
您可以在 mysql 查询中使用 BETWEEN ... AND ... 比较运算符 http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#operator_between