Oldtimer
Oldtimer

Reputation: 45

Get an array of days from mysql table that includes days between From/To dates

I apologize if this is a little simple, but I've been googleing and googleing and just can't seem to find what I'm looking for.

I have a calendar script that allows users to upload events lasting more than one day. It stores the events in a mysql database table that stores the from date and to date in separate columns.

When I attempt to pull the dates from the table and store the days as an array, including those between the from/to dates, so that they can be highlighted in the calendar the script times out telling me that it ran out of memory on the line where dates between the from/to dates. Surely that can't be right as the table only holds my test event and it only lasts one week.

There may be an easier way of doing it all together and I wouldn't be at all surprised if there were other problems with my script, so any and all input is very much welcome. Thanks!

Here's the snipet:

$FromDate=date("Y-m-d", strtotime($Calendar['FromDate']));
$ToDate=date("Y-m-d", strtotime($Calendar['ToDate']));
while($FromDate < $ToDate){
    // below is the line it times out on.
    $StartDate=date("Y-m-d", strtotime("+1 day", strtotime($FromDate))); 
    $EventDays[]=date("d", strtotime($StartDate));
}

Upvotes: 0

Views: 465

Answers (3)

Jacob
Jacob

Reputation: 8334

If you are using PHP 5.3 then this is a great opportunity to use DatePeriod.

<?php
$start = new DateTime('2011-01-01');
$interval = new DateInterval('P1D');
$end = new DateTime('2011-01-28');
// Modify end by one day, so the end date is included.
$period = new DatePeriod($start, $interval, $end->modify('+1 day'));
$eventdays = array();

foreach($period as $date) {
    $eventdays[] = $date->format('d');
} 

var_dump($eventdays);

Upvotes: 1

Dejan Marjanović
Dejan Marjanović

Reputation: 19380

Why don't you...

SELECT * FROM events WHERE datum BETWEEN '2011-4-6' AND '2011-4-12';

with SQL and then do other stuff with PHP?

Upvotes: 0

edorian
edorian

Reputation: 38961

It looks like a simple endless loop since you never change $FromDate or $ToDate so the while(...) never stops and you run out of memory since you always store the same date again and again.

I think you want to rename $StartDate to $FromDate to get the behaviour you decried.

Upvotes: 1

Related Questions