tags:

views:

58

answers:

3

I'm writing a little bit of PHP, but Im a serious nOOb.

I want to compare the current time (The time now) with a timestamp in a table, stored like 1085225495.

If the timestamp is under 1 hour old, then do:

UPDATE TABLE SET visible=0;

Otherwise ignore.

Any ideas in php?

A: 

Here's one way to do it entirely in MySQL

UPDATE foo SET visible=0 
WHERE (UNIX_TIMESTAMP(now())-UNIX_TIMESTAMP(timestamp))<3600;

UNIX_TIMESTAMP() gives you the number of seconds since the epoch, and subtracting the timestamp seconds from the current seconds gives you the age in seconds.

Paul Dixon
A: 
UPDATE TABLE SET visible = 0 WHERE myTimestamp >= UNIX_TIMESTAMP(CURTIME()) - 3600
pix0r
$myQueryUpdate = "UPDATE mdl_course SET visible=0 WHERE myTimestamp >= CURTIME() - 3600 AND metacourse=0";Why doesnt this work?
danit
+1  A: 

Hi,

What about something like this :

update your_table
set visible = 0
where your_timestamp_field >= UNIX_TIMESTAMP(subdate(now(), interval 1 hour))


As explanation, here's a select that might help you :

mysql> select now(), subdate(now(), interval 1 hour), UNIX_TIMESTAMP(subdate(now(), interval 1 hour))\G
*************************** 1. row ***************************
                                          now(): 2009-09-17 18:58:31
                subdate(now(), interval 1 hour): 2009-09-17 17:58:31
UNIX_TIMESTAMP(subdate(now(), interval 1 hour)): 1253203111
1 row in set (0.00 sec)

Here :

  • now() gets the current date and time
  • the subdate() gives 1 hour before now
  • and unix_timestamp() converts that to a unix timestamp


You might also do a substraction of 3600 seconds on UNIX_TIMESTAMP(now()), instead of using subdate... But I like the subdate call : I find it easier to immediatly understand that you want 1 hour (and not a magic number like 3600)

Pascal MARTIN
How can i used that as a PHP bit of code?
danit
You can use that query with `mysql_query` (or the mysqli or PDO equivalents), like you are doing now -- the only thing is that you don't need to do any calculation on the PHP side : everything is done by that one query.
Pascal MARTIN