Cross Vander Cross Vander - 6 months ago 14
PHP Question

PHP Print Date data from database for each date

I have a database called

Holidays
which has a date field to save holiday date called
STARTTIME
, and a duration field to save how many days is the holiday called
DURATION
. I want to collect all data from that table between some month and year, and print the date 1 by 1.

For Example, here's my data at database:

STARTTIME | DURATION
2016-12-09 | 1
2016-12-15 | 5


How to print it in php 1 by 1 per date? So it will result:

2016-12-09
2016-12-15
2016-12-16
2016-12-17
2016-12-18
2016-12-19
2016-12-20


My code now is like this:

//startDate and endDate is get from my filter, this is only for example
$startDate = '2016-01-01';
$endDate = '2016-01-31';
$sqlHol = "SELECT STARTTIME, DURATION FROM HOLIDAYS WHERE DATEVALUE(STARTTIME) BETWEEN DateAdd('m',-1,#$startDate#) AND #$endDate#";
$queryHol = $db->query($sqlHol);
$hols = $queryHol->fetchAll();
echo '<br />';
//testing to print out array result
print_r($hols);
//looping through data from database
foreach($hols as $hol)
{
for($i=1; $i <= $hol[1]; $i++)
{
echo '<br />';
$due = date_create($hol[0]);
echo date_format($due, 'Y-m-d');
$due = date_add(date_create($hol[0]), date_interval_create_from_date_string('1 days'));
echo '<br />';
}
}


And here's my result (the date doesn't increment):

2015-12-09

2015-12-15

2015-12-15

2015-12-15

2015-12-15

2015-12-15

2015-12-15


Anyone know how to create an output like I need?

Answer

It looks like you are writing the due date before you increment it. Try using the loop counter as a way to keep track of how many times you have incremented the date.

foreach($hols as $hol)
{
    for($i=0; $i <= $hol[1]-1; $i++)
    {
        echo '<br />';
        $due = date_create($hol[0]);
        $due = date_add(date_create($hol[0]), date_interval_create_from_date_string(i.' days'));
        echo date_format($due, 'Y-m-d');
        echo '<br />';
    }
}