29

I need to test current time against a datetime from database, if it has been 30 mins then execute code, if not then dont. This is where I am at and I am stuck:

$link = mysqli_connect("hostname", "username", "password", "database");
$q = "SELECT id FROM dwCache ORDER BY id DESC LIMIT 1";
$qu = mysqli_query($link, $q);

while($row=mysqli_fetch_array($qu, MYSQL_ASSOC)){
        $id = $row['id'];
        $cache = $row['cache'];
        $timest = $row['time'];
    }

$newTime = 
$difference = $timest
if($timest >= )

As you can see towards the bottom I lose it as I am not sure what to do.

$timest returns : 2013-02-01 12:36:01 as the format Y-m-d h-i-s

Apologies on double post, other deleted.

4 Answers 4

54

First convert $timest to timestamp

$time = strtotime($timest);

$curtime = time();

if(($curtime-$time) > 1800) {     //1800 seconds
  //do stuff
}
Sign up to request clarification or add additional context in comments.

2 Comments

Is the 1800 seconds, mins or hours?
seconds but all this multiple converting of dates is a waste of time/resources when you can do it all in query and just get back a list of ID's you need to process.
13

do it all in sql statement

SELECT id FROM `dqCache` WHERE `time`<DATE_SUB(NOW(), INTERVAL 30 MINUTE);

This will return everything from your table where the time column is before 30 minutes before now.

Comments

2

I like to use unix timestamps in this situation.

$timest = date('u'); // gets the unix timestamp
$q = "SELECT id 
      FROM `dwCache` 
      WHERE {$timest} - UNIX_TIMESTAMP(`timestamp_col`) > 1800";

Explanation:

This basically calculates the difference between the current time and the time in the table column. If it's higher than 1800 (30 minutes), it will select the row, and your PHP code will be executed.

Advantages

There are some advantages to using this instead of the PHP check you started doing. You will select fewer rows, thus occupy less memory.

PS:

Thumbs up for using MySQLi !

1 Comment

FYI: You should not use this approach in 2020 for SQL injection reasons.
-1
SELECT id FROM dwCache ORDER BY id DESC LIMIT 1

you'll get only id field, it's the first. The second, for time converting: MySQL convert datetime to Unix timestamp

Third: you can convert your time string using strtotime function.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.