RussellHarrower
RussellHarrower

Reputation: 6810

PHP MySQL if time is 5 minutes more or over then the stored time

I want to the script to delete the row if the difference between a timestamp that is stored in the db and the current time is 5 minutes or more.

Example

A row in db has 2011/12/25 10:00
the current time is 2001/12/25 10:06

I want it to remove the db row.

Upvotes: 1

Views: 2253

Answers (4)

CodeCaster
CodeCaster

Reputation: 151594

Why the cron suggestions? You can easily call the very easy delete statement on every page view. At the moment that becomes a bottlenecks (and then we're talking about either a massively underengineered table structure or a very busy site), it may become appropriate to see why the query is so slow. Run an explain query, apply some indexes, and so on. If the problem then still exists, it could be that it's simply too much work to let a visitors wait for, and then it's time for cron.

Until then, simply execute the following query on each page view:

delete 
from 
    YourTable 
where 
    adddate(YourDateTimeColumn, interval 5 minute) < now()

Upvotes: 3

Adam Luz
Adam Luz

Reputation: 21

The code above is slightly wrong. It should be

delete 
from 
    YourTable 
where 
    adddate(YourDateTimeColumn, interval 5 minute) < now()

There was an s on minute, it shouldn't be there.

Upvotes: 2

Liam Allan
Liam Allan

Reputation: 1115

try this, not tested tho:

$query = mysql_query("SELECT * FROM table");
$result = mysql_fetch_array($query);

$id = $result['id'];
$timestamp = strtotime($result['timestamp']);
if($timestamp < time()-300){
 mysql_query("DELETE FROM table WHERE id=".$id."");
}

Upvotes: -3

SuperTron
SuperTron

Reputation: 4233

If you are in Linux, you could write a chron job that executes a php(or almost any other language) script that does this. As far as I know, a database will not have this sort of functionality built in, you need to write code that actively does it. Hope this helps.

Upvotes: 0

Related Questions