简体   繁体   中英

PHP MySQL select rows where date time value within the last n minutes

I have a MySQL table that looks a little like this:

Timestamp           | Content
-----------------------------------------
2018-10-28 12:59:47 | "Some string"
2018-10-29 04:13:48 | "Some other string"

The Timestamp column is of the datetime type. Values are being created for insertion into the column using the PHP date() function. For example, date("Ymd H:i:s")

I'd like to use PHP to select all rows where the timestamp value is within the last n minutes.

I know how to select all rows where the date is a particular value. For example, the following will select all rows where the timestamp matches the current date/time:

mysqli_query($link, "SELECT * FROM tablename WHERE Timestamp = '" . date("Y-m-d H:i:s") . "'");

How would I make a query to select all rows where the Timestamp value is within the last, say, 49 minutes ?

Use this query (There's no need to involve PHP date functions, when MySQL has them built in. See DATE_SUB() for more info):

SELECT *
FROM tablename
WHERE Timestamp > DATE_SUB(NOW(), INTERVAL 49 MINUTE)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM