Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save array to DB

Tags:

arrays

php

mysql

I'm new to PHP Arrays... but I have created an array to get all dates between 2 dates that have been submitted in a form.

See below:

$endDate=$_POST[todate];
            $startDate =$_POST[fromdate];

print_r(getDatesFromRange( "$datef", "$dateto" ));

function getDatesFromRange($startDate, $endDate)
{
    $return = array($startDate);
    $start = $startDate;
    $i=1;
    if (strtotime($startDate) < strtotime($endDate))
    {
       while (strtotime($start) < strtotime($endDate))
        {
            $start = date('Y-m-d', strtotime($startDate.'+'.$i.' days'));
            $return[] = $start;
            $i++;
        }
    }

    return $return;
}

This results in the below

Array ( [0] => 2016-10-10 [1] => 2016-10-11 [2] => 2016-10-12 [3] => 2016-10-13 [4] => 2016-10-14 [5] => 2016-10-15 [6] => 2016-10-16 [7] => 2016-10-17 [8] => 2016-10-18 [9] => 2016-10-19 )

Is there a way to save each of these dates to a MySQL database using PHP?

like image 796
Shane Avatar asked Jul 18 '26 02:07

Shane


1 Answers

After you get the dates from range do loop to insert each value of the array.

$date = getDatesFromRange( "$datef", "$dateto" );
    foreach ($date as $d){
        $sql = "INSERT INTO MyDatabase (dateCol)
                VALUES ('$d')";
        if ($conn->query($sql) === TRUE) {
            echo "New record created successfully";
        } else {
            echo "Error: " . $sql . "<br>" . $conn->error;
        }
    }   

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!