I want to output all entries from the database within this calendar week based on a given date.
Example:
I have entered
2024-11-20
Check whether there are any other entries in the calendar week of this date that should be output.
I tried the following:
$wochenzieldaten = $DB->get_records_sql( "SELECT * FROM {schultimer_wochenziel}
WHERE wzuserid = {$getuserid}
AND datum BETWEEN DATE_SUB(CURRENT_DATE(), INTERVAL 1 WEEK)
AND CURRENT_DATE()" );
2
Answers
If you do your date calculations in PHP then you’ll get a more portable query. PHP has a very nice feature in
strtotime()
andnew DateTime()
that allows you to use flexible relative descriptions, which you can use to find the week bounding dates. In this case, if the target date is already a Monday, then that’s the start of our range. Otherwise, we want to go backwards from the target date until we find the first Monday. This can be done withprevious Monday
in the date string. Once we find the range start, we can calculate the range end with the+6 days
relative string.This yields:
Note this will work just fine across year boundaries:
Yields:
Now you can use these values in your query, to find all the records that exist within that week:
This might be what you’re looking for:
Or replace all
CURRENT_DATE()
by a placeholder like:date
, if theCURRENT_DATE()
in your question was only for experimenting.