Skip to content
Advertisement

How do I get rows for last 24 hours by unixstamp

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

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement