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.




Use "select max(datetime_field) from tblname" to get the most recent value for the Datetime field.




$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 todatefield and change select like:

select `datefield` from `table` where `datefield` >= '$date' limit 1

People are also looking for solutions to the problem: How to insert value into MySQL table with PHP


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.