简体   繁体   中英

PHP MySqli Insert Multiple Dates of a Date Range

How can i insert every date from the following code to a database using mysqli?

$start_date = '2012-01-01';
$end_date = '2012-01-10';

$start    = new DateTime($start_date);
$end      = new DateTime($end_date);
$interval = new DateInterval('P1D');
$period   = new DatePeriod($start, $interval, $end);

 foreach ($period as $day) {
    $tag  = $day->format('Y-m-d');
}

You could insert multiple rows by formatting this $tag as an array.

Try this:

foreach ($period as $day) {
    // Do stuff with each $day...
    $tag[]  = "('".$day->format('Y-m-d')."')"; // Change this line

}

$values = implode(",", $tag);

$sql = "INSERT INTO my_table (date) VALUES ".$values;

Assuming your table name is "my_table" and your field is "date".

Hope this helps.

Peace! xD

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM