简体   繁体   中英

Select data that was added the last 7 days

I have a table where the time is a date type. I would like to select all the records that were added the last 7 days and then out put them in an xml file. I can select all data and output it fine without a WHERE statement.

Here is the code:

$query_feed = "SELECT * FROM keysound_data WHERE time >=DATE_SUB(CURDATE(), INTERVAL 7 DAY AND time <= CURDATE()";
$feed = mysql_query($query_feed, $dconn) or die(mysql_error());
$row_feed = mysql_fetch_assoc($feed);
$totalRows_feed = mysql_num_rows($feed);



echo'<items>';
while ($row_feed = mysql_fetch_assoc($feed)){
            echo'

        <item>
            <name>'.$row_feed['Name'].'</name>
            <email>'.$row_feed['email'].'</email>
            <date>'.$row_feed['Date'].'</date>
            <description>'.$row_feed['Make'].' '.$row_feed['Model'].' '.$row_feed['Type'].'</description>
            <logon>'.$row_feed['Logon'].'</logon>
            <category>'.$row_feed['Type'].'/'.$row_feed['Make'].'</category>
            <product_search_code>'.$row_feed['Product_search_code'].'</product_search_code>
            <order_ref>'.$row_feed['Invoice'].'</order_ref>
            <product_link>'.$row_feed['Product_link'].'</product_link>
            <customer_ref>'.$row_feed['Invoice'].'</customer_ref>
            <amount>'.$row_feed['Price'].'</amount> 
            <currency>GBP</currency>
        </item>'; 
 }
 echo '</items>';

Not sure what's going wrong. Any help welcome

You are missing a closing bracket.

Try this-

time >=DATE_SUB(CURDATE(), INTERVAL 7 DAY) AND time <= CURDATE()

You're missing a bracket in your SQL to close DATE_SUB function.

Try this:

SELECT * 
FROM keysound_data 
WHERE 
    time >=DATE_SUB(CURDATE(), INTERVAL 7 DAY)
    AND time <= CURDATE()

Better yet, you could use BETWEEEN to optmize your query:

SELECT * 
FROM keysound_data 
WHERE 
    time BETWEEN (CURDATE() - INTERVAL 7 DAY) AND CURDATE()

EDIT: As @spencer7593 noticed, CURDATE() - INTERVAL 7 DAY should be used instead of DATE_SUB(CURDATE(), INTERVAL 7 DAY) for even better optimization. The query above was updated to make use of that.

SELECT * FROM keysound_data(now()-间隔7天)和now()之间的时间

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