user3081581
user3081581

Reputation: 65

Insert database with while loop

I want to create a function that select the begin date and end date and then insert into the database. I want to insert the date for every 4 days from 30/8 til 30/9 to the database...

For example:

table 
row 1 = 30/8 
row 2 = 3/9
row 3 = 7/9 
row 4 = 11/9 ... and so on 

My php:

<?php
$con = mysql_connect("localhost", "root", "root");
mysql_select_db("test", $con);

$start_date= "2015-08-30";
$end_date= "2015-09-30";

$insert = "INSERT INTO calendar(date)......";

if(mysql_query($insert,$con)) {
    echo "<script> alert('Insert Successful'); </script>";
}
else {
    echo "<script> alert('Insert Unsuccessful'); </script>";
}

while (strtotime($start_date) <= strtotime($end_date)) {
    //echo "$start_date <br>";
    $start_date = date ("Y-m-d", strtotime("+4 day", strtotime($start_date)));
}

Upvotes: 0

Views: 61

Answers (1)

MenukZ
MenukZ

Reputation: 79

Think this is what your searching for... let me know anything needed to change...

    <?php

$start_date= "2015-08-30";
$end_date= "2015-09-30";

$inc_val = 4;

$start_con_to_time = strtotime($start_date);
$end_con_to_time = strtotime($end_date);

$days_between = ceil(abs($end_con_to_time - $start_con_to_time) / 86400);

for($x=$inc_val+1; $x<=$days_between;)
{
    echo date('Y-m-d', strtotime($start_date. ' + ' . $x . 'days'));
    echo ' : Add database code here <br>';
    $x+=$inc_val;
}

?>

Upvotes: 1

Related Questions