Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

Querying MySQL depending on the Day of the Week

I'm trying to query my database and retrieve data based on the day of the week. If today is Sunday, I wish to retrieve all of the data entries which have Sunday as the relevant day of the week in the 'day of the week' column.

When Monday rolls around, php will read that the day of the week is different and then pull only the data from the database which features 'Monday' in the column for day of the week. Am I missing a simple way of doing this?

Please help!

Best regards, Harry

1 Answer

Nicholas Vandenbroeck
Nicholas Vandenbroeck
4,599 Points

You could write a query like this:

"SELECT * FROM table WHERE day_of_the_week_column = " . date('l');

The query then selects the data that belongs to the day that the date function returns. I added the l (lowercase L) to format the date as a day of the week.

By the way, you shouldn't store the day of the week in a separate column. There are date functions available in SQL to get the day of the week.

Hi Nicholas, thanks very much for your answer. I eventually found a solution that kind of meets in the middle!

My code now looks like this:

$results = $db->query("SELECT blah FROM table_name WHERE weekday = DAYNAME(CURDATE()) ");