php 如何使用PHP从MySQL中选择特定时间范围内的记录?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5530984/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you select records with a certain time range from MySQL using PHP?
提问by NiLL
How to choose from MySQL, using PHP, records that were created for a certain period of time, if each record has creation time in timestamp?
如果每个记录在时间戳中都有创建时间,如何从 MySQL 中选择,使用 PHP,创建一段时间的记录?
回答by Sebastian Paaske T?rholm
You do a query similar to:
您执行类似于以下内容的查询:
SELECT *
FROM table
WHERE creation_time BETWEEN '2011-01-01 00:00:00' AND '2011-03-01 00:00:00'
Here it'll select all entries that have a creation time between January 1st, 2011 and March 1st, 2011.
在这里,它将选择所有创建时间在 2011 年 1 月 1 日和 2011 年 3 月 1 日之间的条目。
回答by Chuck Burgess
First you need to connection to the database, then run the query against the specific table you want to get data from,
首先,您需要连接到数据库,然后针对要从中获取数据的特定表运行查询,
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$result = mysql_query("SELECT * FROM `table` WHERE `date_field` BETWEEN 'date1' AND 'date2'");
if (!$result) {
die('Invalid query: ' . mysql_error());
}
while($row = mysql_fetch_row($result)){
echo $row[0].','.$row[1]...
}
mysql_close($link);
?>
You can find more information at - link
您可以在 -链接中找到更多信息
回答by EmCo
You can do it like this:
你可以这样做:
SELECT fields....
FROM tables
WHERE dates BETWEEN 'date1' AND 'date2';
回答by Hugo Mota
you can do something like this:
你可以这样做:
$valid = strtotime('-7 days'); //define your valid time
$valid = strtotime('-7 days'); //define your valid time
then just use it to select
然后用它来选择
"SELECT ******* WHERE time > $valid";
"SELECT ******* WHERE time > $valid";
but that's me. i don't like to work with dates directly in SQL. maybe you don't like too (:
但这就是我。我不喜欢直接在 SQL 中处理日期。也许你也不喜欢 (: