0

Im trying to insert date with range of date using of inputs

here is what i got in HTML

<input type="date" id="startdate" name="startdate"/> //ex. value="2018-12-18"
<input type="date" id="enddate" name="enddate"/> //ex. value="2018-12-31"

my PHP code is

$db = mysqli_connect('localhost', 'root', '', 'database');
if(isset($_POST['submit']))//this is my submit button
{
    $startdate = $_POST['startdate']
    $enddate = $_POST['enddate']

    $query = "INSERT INTO appointment (date) VALUES (//i want to insert all covered date from start to end)";
            mysqli_query($db, $query);
}

my database table is column is id(auto increment) date and schedule. how can i input the date from "2018-12-18 to 2018-12-31 in row"

i want my output in my table like this:

|   date   |
|2018-12-18|
|2018-12-19|
|2018-12-20|
|2018-12-21| //so on and so fort until reach the end date
Kiel Dred
  • 31
  • 1
  • 8
  • You can iterate over each date within the range and insert each with separate queries. There might be a way to do it all in one SQL query, though. – rpivovar Dec 17 '18 at 16:28
  • Why not just have the start and end date as 2 columns? https://3v4l.org/HdCQW could work i guess.. – user3783243 Dec 17 '18 at 16:29
  • @user3783243 how can i remove automatic +1day to start time – Kiel Dred Dec 17 '18 at 19:57
  • Not sure what you mean, which date should be removed? Maybe look at https://stackoverflow.com/questions/44365151/how-to-create-a-date-range-with-php – user3783243 Dec 17 '18 at 20:22

1 Answers1

-1

This is taken from another stackoverflow answer.

You could take a look at the DatePeriod class:

$period = new DatePeriod(
     new DateTime($_POST['startdate']),
     new DateInterval('P1D'),
     new DateTime($_POST['enddate'])
);

Which should get you an array with DateTime objects.

To iterate

foreach ($period as $key => $value) {
    //$value->format('Y-m-d')       
}

You can do it in one query like so:

$query = "INSERT INTO appointment (date) VALUES";
foreach ($period as $key => $value) {
     $date = $value->format('Y-m-d');
      $query .= "('$date'),";       
}

Which gives you:

INSERT INTO appointment (date) VALUES('2010-10-01'),('2010-10-02'),('2010-10-03'), 
('2010-10-04'),

You might have to delete the final comma.

$query = rtrim($query, ',');
Baasic
  • 86
  • 6