是否有一个在php中运行的查询,允许您在两个日期之间插入所有日期?
例如,进入03/20/2012和03/20/2013,并在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/2012Note
我不想生成这个列表(我研究的问题只回答了如何生成一个列表),我想填充一个MySQL DB
任何帮助都将不胜感激。
发布于 2012-03-29 08:39:06
您可以使用此函数生成日期数组。
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();
}发布于 2012-03-29 08:38:16
填充DB的最简单方法是生成SQL insert查询列表。
因此,如果您可以生成一个执行类似insert into table (... , date_from, date_to, ... ) values ( ..., val1, val2, ...)的查询的列表,那么您就可以运行这些查询并填充表。
发布于 2012-03-29 08:39:35
$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}
");https://stackoverflow.com/questions/9921688
复制相似问题