简体   繁体   中英

SQL SELECT date from 10 days ago failed

I'm havig some trouble with SQL:

First, I insert the current date, using PHP-time():

mysql_query("
   INSERT INTO applicants (
      date_last_applied
   )
   VALUES (
      " . time() . "
   )
");

This works just fine. However, I only want to execute an action when that ^ was inserted 10 days ago:

$result = mysql_query("
   SELECT * FROM applicants WHERE date_last_applied < DATE_SUB(NOW(), INTERVAL 10 DAY)
");
while ($row = mysql_fetch_array($result)) 
    echo $row['id_member'];

Although it should work (IMO), it doesn't. D:

For possible solutions: it's not an option to use an other timeformat, because I'm using this format on my entire site.

我认为将date_sub resutl转换为unixtime将解决您的问题。

date_last_applied < UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 10 DAY))

while inserting rows you are using time (time()) of the local machine. But while retrieving rows you are using the mysql server's time (NOW()). Are you sure they match exactly and will continue to do so. You should try to use mysql server time everywhere.

Also you are inserting rows in applicants and retrieving from DDFS_applicants. May be that is the problem here

Since you are using a timestamp, and I'm guessing that you don't use a Data time field, Converting should solve your problem. But there is a but!

The UNIX_TIMESTAMP is always in GMT, so it could be that your PHP time() isn't the same as your UNIX_TIMESTAMP. If you find out its the same, then you should be good!

date_last_applied < UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 10 DAY))

Ok, thanks for your help, y'all. This code works flawlessly:

 //get member's info
$result = mysql_query("
   SELECT * FROM DDFS_applicants 
   WHERE FROM_UNIXTIME(date_last_applied, '%Y %D %M') = FROM_UNIXTIME(UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 1 DAY)), '%Y %D %M')
");
while ($row = mysql_fetch_array($result)) {
    echo $row['id_member'];

(So it works even to check if the date is the exact same date. If you want, you can even add hours to it, but I chose not to.)

Source: http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_date-sub

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