简体   繁体   中英

PHP MySQL - limit query result by time difference

This would be an example of database table:

在此处输入图片说明

PHP script should limit query result between NOW and time before 30 seconds

To be clear:

In current time is 2012-03-23 03:28:00 and database is as descibed in example, resoult should be: "guest"

This is a part of PHP script.

<?php
    $con = mysql_connect("localhost", "user", "pass");
    if (!$con) {
        die('Could not connect: '.mysql_error());
    }

    mysql_select_db("db", $con);

    $result = mysql_query('SELECT * FROM table LIMIT BY ...???...... ');
        while ($row = mysql_fetch_array($result)){
         echo $row['username'];
        }

    mysql_close($con);
?>

You don't want a LIMIT , you want a WHERE

$result = mysql_query(
'SELECT * FROM table WHERE `timestamp` > NOW()- INTERVAL 30 SECOND '
);

In SQL, a LIMIT clause executes the whole query, and then only takes a certain "range" of consecutive rows. You can say "The first 50", or "From 20 to 30".

A WHERE clause limits the query on certain criteria, such as field contents. That is what you want here.

... WHERE (unix_timestamp(NOW()) - unix_timestamp(timestamp))<30 ..

要么

WHERE TIME_TO_SEC(TIMEDIFF(NOW(), timestamp))<30
    $result = mysql_query('SELECT * FROM table where date_sub(now(), timestamp ) < your_time_interval ');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM