简体   繁体   中英

How do you select records with a certain time range from MySQL using PHP?

How to choose from MySQL, using PHP, records that were created for a certain period of time, if each record has creation time in timestamp?

You do a query similar to:

SELECT *
FROM table
WHERE creation_time BETWEEN '2011-01-01 00:00:00' AND '2011-03-01 00:00:00'

Here it'll select all entries that have a creation time between January 1st, 2011 and March 1st, 2011.

First you need to connection to the database, then run the query against the specific table you want to get data from,

<?php
    $link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
    if (!$link) {
        die('Could not connect: ' . mysql_error());
    }

    $result = mysql_query("SELECT * FROM `table` WHERE `date_field` BETWEEN 'date1' AND 'date2'");
    if (!$result) {
        die('Invalid query: ' . mysql_error());
    }

    while($row = mysql_fetch_row($result)){
        echo $row[0].','.$row[1]...
    }

    mysql_close($link);
?>

You can find more information at - link

You can do it like this:

SELECT fields.... 
FROM tables
WHERE dates BETWEEN 'date1' AND 'date2';

you can do something like this:

$valid = strtotime('-7 days'); //define your valid time

then just use it to select

"SELECT ******* WHERE time > $valid";

but that's me. i don't like to work with dates directly in SQL. maybe you don't like too (:

Most of the time when we create an entry into the database we also save the time when that specific entry is created (mostly in the created_at column). If you want to get records that are in a specific range of time, then the following query will be helpful:

SELECT * FROM tableName WHERE created_at between now() - interval 30 minute and now() - interval 10 minute;

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