0

I have the following query:

$yesterday=date("Y-m-d",mktime(0,0,0,date("m"),(date("d")-1),date("Y")));
$sql = "SELECT messages FROM user WHERE sent_date='".$yesterday."'";

With it I select all the messages sent to the users yesterday.

In my database sent_date looks like: 2010-12-28 11:55:30

But with $yesterday I get: 2010-12-28

So I get 0 results.

How can I modify my query so I can select all the messages from yesterday no matter the hour?

Thanks a ton

3 Answers 3

3

You should use MySQL Date functions for that (assuming the column is a datetime).

SELECT messages FROM user WHERE sent_date = DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY);

or always from 00:00

SELECT messages FROM user WHERE sent_date = DATE_SUB(CONCAT(CURDATE(), ' 00:00:00'), INTERVAL 1 DAY);

If this is not giving any results, please edit your question with more info. You exact schema, how do you insert data and ensure that there are valid rows inside the table.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for noting. I've integrated it into the answer.
I'm trying both but still 0 results .. I'm trying to debug the mysql date functions now ...
See my edit; the date functions are fine. I'm sure there is something wired going on with your data.
2

Perhaps by using

$sql = "SELECT messages FROM user WHERE date(sent_date)='".$yesterday."'";

That way you don't use the time in the datetime for comparison.

1 Comment

Try @DrColossos's suggestion above and do it all in MySQL instead of setting in PHP first: SELECT messages FROM user WHERE sent_date = DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY);
1

You could do a BETWEEN and put in a starting and ending time concatenated on the $yesterday...

Actually... what the next post suggests is better if you want the full date.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.