Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
794 views
in Technique[技术] by (71.8m points)

php - MySQL Query - get records based on current date

I am setting a Cron and I want to do various of functions on records which match the current day

My users table:

Username      registration_date    expiration_date
behz4d        2012-01-19 21:55:44  2013-01-23 11:15:24
test          2012-05-24 17:42:13  2013-04-12 17:23:19
...

Now I want to get the users which their expiration_date is TODAY I simply could query the tables, get their expiration_date in an array, and compare that date with today date, like:

$current_date = date("Y-m-d");
$query = mysql_query("SELECT username FROM users");
while($row = mysql_fetch_array($query)){
    $users_array[] = $row['username'] . "->" . substr($row['expiration_date'], 0, 10);// since I don't care about the exact time, I need to get the users who their expiration DAY is today 
}
foreach($users_array $username as $expiration_date){
    if($expiration_date == $current_date)
         $my_target_users[] = $username;
}

But this seems a little odd, I mean there should be another way...

Is there anyway that I could say like expiration_date = TODAY ?

Anybody could help me with this? Thanks in advance


UPDATE:

How about getting users who their expiration day is 3 days from today? I want to send an email to them and let them know that their account will be expired in 3 days... Should I just do:

... WHERE expiration_date >= CURRENT_DATE AND expiration_date < CURRENT_DATE + INTERVAL 3 DAYS

!?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
SELECT username FROM users WHERE DATE(expiration_date) = CURRENT_DATE

However, this requires a(n inefficient) full table scan. If you have an index on expiration_date, you should instead use:

SELECT username
FROM   users
WHERE  expiration_date >= CURRENT_DATE
   AND expiration_date <  CURRENT_DATE + INTERVAL 1 DAY

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...