输入开始日期和结束日期,并将两者之间的日期插入数据库


Entering a start date and an end date and inserting the dates in between into db

是否有一个在php中运行的查询可以让您在两个日期之间插入所有日期?

例如,输入2012年3月20日和2013年3月2日,并用两者之间的所有日期填充mysql?

我为一家航空公司制作了一个票务系统,他们每天有13个航班从20多个地点起飞,手动插入变得很乏味。

我想插入日期以及每天的值

例如。

 FROM                TO              Date_From              Date_To
     Dar Es Salaam      Zanzibar         03/20/2012             03/21/2012
     Dar Es Salaam      Zanzibar         03/21/2012             03/22/2012

注意

我不想生成这个列表(我研究的问题只回答了如何生成列表)我想流行MySQL DB

如有任何帮助,将不胜感激

您可以使用此函数生成日期数组

function dateRange( $first, $last, $step = '+1 day', $format = 'd/m/Y' ) {
    $dates = array();
    $current = strtotime( $first );
    $last = strtotime( $last );
    while( $current <= $last ) {
        $dates[] = date( $format, $current );
        $current = strtotime( $step, $current );
    }
    return $dates;
}
$dateRange = dateRange("03/20/2012", "03/20/2013);

然后在数组上迭代以插入数据

$stmt = $dbh->prepare("INSERT INTO table (from, to, date_from, date_to) VALUES (:from, :to, :datefrom, :dateto)");
$stmt->bindParam(':from', "Dar Es Salaam");
$stmt->bindParam(':to', "zanzibar");
$stmt->bindParam(':from', $datefrom);
$stmt->bindParam(':to', $dateto);
for ($i = 0; $i < count($dateRange); $i++){
   $datefrom  = strototime($dateRange[$i]);
   $dateto  = strototime($dateRange[$i+1]);
   $stmt->execute();
}

填充数据库的最简单方法是生成SQL插入查询的列表。

因此,如果您可以生成一个类似于insert into table (... , date_from, date_to, ... ) values ( ..., val1, val2, ...)的查询列表,那么您就可以运行这些查询并POPULATE表。

$int_date_from = strtotime($str_date_from); // Will be used often
$int_days = (strtotime($str_date_to) - $int_date_from); // Calculate difference in seconds
$int_days /= floor(60 * 60 * 24); // Seconds to days
$arr_values = array();
for($i = 0; $i < $int_days; $i++) {
    $str_new_date_from = date('m/d/Y', strtotime("+{$i} Days", $int_date_from));
    $str_new_date_to = date('m/d/Y', strtotime('+'.($i + 1).' Days', $int_date_from));
    $arr_values[] = "('{$str_from}', '{$str_to}', '{$str_new_date_from}', '{$str_date_to}')";
}
$str_values = implode(', ', $arr_values);
mysql_query("
INSERT INTO table
VALUES {$str_values}
");