tags:

views:

79

answers:

3

I have this;

$long = "86400";
$query = "SELECT * FROM users WHERE unixdate = UNIX_TIMESTAMP()-$long 
          ORDER BY unixdate DESC";

But it doesn't work. I would like to show all new users within 24 hours

+7  A: 

Use > instead of =. At the moment, you are querying for entries created at a certain second which will hardly ever match.

Pekka
+1  A: 

You're looking for new users within the last 24h, not exactly 24h. So you have to use the > (greater than) operator instead of = (equals).

$long = "86400";
$query = "SELECT * FROM users WHERE unixdate > UNIX_TIMESTAMP()-$long ORDER BY unixdate DESC";

By the way, PHP has a function equivalent to MySQL UNIX_TIMESTAMP() function: time();

Lekensteyn
+3  A: 

You can do that query completely in MySQL with

SELECT col1, col2, otherCols
    FROM yourTable 
    WHERE timestamp_col > (NOW() - INTERVAL 24 HOUR)

The expression (NOW() - INTERVAL 24 HOUR) returns the date 24 hours ago. MySql is smart enough to handle comparisons between Time related column types.

If timestamp_col is not a time related type, but something like a varchar or int column you have to use FROM_UNIXTIME on the column or adjust the above query to read

SELECT col1, col2, otherCols
    FROM yourTable 
    WHERE timestamp_col > UNIX_TIMESTAMP( NOW() - INTERVAL 24 HOUR )

See DATE_SUB and DATE_ADD in the MySql Manual.

Gordon
+1 for INTERVAL
Rocket
you need to translate it to timestamp then
Col. Shrapnel
*sigh* this place is getting worse by the day. downvote for what?
Gordon
I didn't downvote, but I think this needs an additional `FROM_UNIXTIME()` (the OP seems to be working with a varchar/int timestamp column). Other than that, +1
Pekka
@Pekka I did a quick test setup with a *timestamp* column and it worked fine.
Gordon
unix timestamp not mysql timestamp
Col. Shrapnel
@Gordon if it's not a timestamp column but a varchar or int one (some people used to like to do that in the past :), it'll do an auto-cast of the date to `char` and compare against that, with unwelcome results. Depends on the OP's table structure
Pekka
@Pekka ok, yes. If it's an int or varchar column, then you have to use `FROM_UNIXTIME`
Gordon