Php mysql delete data every 10mins

Hello forums

I’m making a visitors online for a wordpress blog and I am logging a session hash in mysql database (I’m using a session hash created by vbulletin as it is integrated with my wordpress)

if (isset($_COOKIE['bbsessionhash'])){
//insert to databse query + current time
}

how do I delete this data from mysql every 5 mins. I’m not asking for exact code just an idea…

thanks

It might not be important to actually delete it on time. You could just filter out the records that are older than 5 minutes when doing a select. Cleanup never needs to be done then, or you could do it on a less rigid schedule.

But, if you really need to delete, run a cron job every 5 minutes.

The simplest method is making a mysql query which deletes records older than 5 minutes from now.

Would it not be easier implementing a database session handler and let php’s built in garbage collection handle the clean-up?

Thanks everyone heres my solution:

when visitor visits the site 1 session is inserted in the databse with current time and expiry time. When another visitor visits the site php will check all the sessions and check if it has expired if it is it will mark it expired.

then my query looks something like this

$q =mysql_query(“SELECT stats FROM table WHERE stats !=‘expired’”);
$number_of_visitors = mysql_num_rows($q);
echo '$number_of_visitors;

Cheers, I know there are tons of better solution than this but I’ll stick with it.

Indeed, there are.
And you choose worst one :slight_smile:

Right code must be like this (as you were told):

define("VISIT_TIMEOUT", 300);
mysql_query("DELETE FROM table WHERE updated < unix_timestamp() - ".VISIT_TIMEOUT);
$res=mysql_query("SELECT count(*) from table");
$row=mysql_fetch_row($res);
echo $row[0];

Also,

//insert to databse query + current time

There must be not only insert but update too
It can be combined into query

mysql_query("REPLACE INTO table SET updated=unix_timestamp() WHERE hash='$hash'");

Anyway, you don’t need your own table at all. You can use vbulletin’s session table. With query like this

$res=mysql_query("SELECT count(*) FROM table WHERE updated > unix_timestamp() - ".VISIT_TIMEOUT");

May be this script will be useful for someone: http://freshmeat.net/projects/phpcron/

It is PHPcron project.

If you really need to delete your records every 5 minutes, just set a cron job to run that query every 5 min.

Thanks Shrapnel_N5 I’ll try this one first thing in the morning when I wake up

No cron job for this one, it will send notification emails to my email every 5 mins, too much bandwidth wasted.

Whats this got to do with this thread…and no I don’t find it useful, cpanel has a built in GUI for setting up Cron Jobs.

REPLACE might not be the best option depending on the structure of the table and the storage engine used.