Jump to content

INSERT for date range


Canman2005

Recommended Posts

Hi all

 

I have the following table

 

  `date` date
  `day` int(2)
  `month` int(2)
  `year` int(4)

 

If I pass a date range in PHP, such as

 

$datefrom = '2009-02-20';

$dateto = '2009-02-25';

 

How can I get it to INSERT a record for every date between that date range?

 

So with that example date range, it would do

 

INSERT INTO `dates` (`date`, `day`, `month`, `year`) VALUES
('2009-02-20', '20', '02', '2009'),
('2009-02-21', '21', '02', '2009'),
('2009-02-22', '22', '02', '2009'),
('2009-02-23', '23', '02', '2009'),
('2009-02-24', '24', '02', '2009'),
('2009-02-25', '25', '02', '2009')

 

but not do an INSERT if any of those dates already exists in the database.

 

Any help would be great

 

Thanks very much

 

Ed

Link to comment
https://forums.phpfreaks.com/topic/178017-insert-for-date-range/
Share on other sites

Figured it out

 

<?php
function dates($start,$end) {
$ret = array();
$sts = strtotime($start);
$ets = strtotime($end);
if ($ets < $sts) return (false);
for($i=$sts;$i<=$ets;$i+=86400)
$ret[] = $i;
return($ret);
}

$dates = dates('2009-01-20','2009-02-05');
if (is_array($dates))
foreach ($dates as $dt)
echo date('Y-m-d',$dt) . '<br>';
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.