Jump to content

loop based on dates


searls03

Recommended Posts

Hi,

I am completely stuck on this.

I am trying to allow the user to select a start day and end day.  then the system adds two weeks to the start day and each previous calculation (ie intervals of 0 weeks, 2 weeks, 4 weeks, etc. from the start day) until the end date is reached.  I would also like each of these dates to be inserted into my database.

 

I have no clue as to where to even start with this.  I know I will need some kind of loop based on days, but I am not sure how I would write this.  

 

I suppose this would be the basic structure of the query, but not sure how to incorporate this loop that I need.

mysql_query("INSERT INTO events (title, date)
VALUES ('$title', '(current date that the loop is in)')");
mysql_error();

can anyone help me out with this?  thanks in Advance!

Link to comment
Share on other sites

the php datetime functions has a DatePeriod class that allows iteration over a set of dates -

$start = '2014-05-01';
$end = '2014-07-01';

$start_date = new DateTime($start);
$end_date = new DateTime($end);
$end_date = $end_date->modify('+1 day'); // if you need the end date in the range (DatePeriod is not inclusive of the end date)
$interval = new DateInterval("P14D"); // 14 days
$dates = new DatePeriod($start_date, $interval, $end_date); // Traversable date range
foreach($dates as $date){
    echo $date->format('Y-m-d') . '</br>';
}
Link to comment
Share on other sites

Or just use a for or while loop:

<?php

$start = '2014-05-01';
$end = '2014-07-01';

$current_date = new DateTime($start);
$end_date = new DateTime($end);

while ($current_date <= $end_date)
{
    echo $current_date->format('Y-m-d'), '<br>';
    $current_date->modify('+2 weeks');
}
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.