I have a database table containing dates when events start. An event ends when the next one starts. Given a start date and end date, I’m looking to create an array of dates with their corresponding event ID.
Currently I run an SQL query for each date. Pseudocode:
$currDate = $startDate
While $currDate++ < $endDate
echo $currDate . " - " . dbQuery("SELECT TOP 1 ID FROM events WHERE eventDate <= '$currDate' ORDER BY eventDate DESC");
Loop
How can I make this more efficient (in PHP)?
EDIT: Thanks for the answers however I realise the question wasn’t clear. Managed to write some SQL that executes fast (<10ms) on my server for dates spanning years.
Here’s the solution using SQL:
SQL Fiddle
MS SQL Server 2008 Schema Setup:
Query 1:
Results: