简体   繁体   中英

MySQL date comparison from PHP

I would very much appreciate your help.

I have a mysql db that contains a Datetime field. In that field I have a particular date and time, for example:

2013-10-03 22:28

I then have a PHP script that gets a particular date and time from the $_GET command, values separately: year, month, day, hour, minute.

From this GET I created a Date as follows:

$datum = $year."-".$month."-".$day." ".$hour.":".$minute.":".$seconds;
$date = date('Y-m-d H:i',strtotime($datum));

What I need to do now is somehow compare this new date I created with the last date value in the database (the most recent). The point is that after I compare this I want to check whether the last value in the db is older than 5 minutes and only then do a particular action (insert new row), and if the last date in the db is newer than 5 minutes, do nothing.

使用“从tblname中选择max(datetime_field)”来获取Datetime字段的最新值。

$now = new DateTime();
$dateFromDB = new DateTime($someValueFromYourDataBase);

// subtract 5 minutes from now and compare with the stored timestamp
if ($now->sub(new DateInterval('PT5i') > $dateFromDB) {
    // database timestamp is older - do something
}

you can use SQL like this:

select count(*) from `table` where `datefield` >= '$date'

$date can be calculated like

 $date = date('Y-m-d H:i', strtotime($datum) - 5*60);

5*60 - it is 5 minutes

for performance reason I suggest you to add index to datefield and change select like:

select `datefield` from `table` where `datefield` >= '$date' limit 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.

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