Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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()) ");