我想选择日期范围内的所有星期一,并将日期保存在数据库中。这是我试过的代码。但它只保存了最后的日期。我想保存所有的星期一。请你能帮帮我吗?
$startDate = '2011-08-10';
$endDate = '2011-10-23';
for ($i = strtotime($startDate); $i <= strtotime($endDate); $i = strtotime('+1 day', $i)) {
if (date('N', $i) == 1) {
$query = "INSERT INTO class(Day, Date) VALUES('Monday', '".date('Y-m-d', $i)."')";
}
}
答案 0 :(得分:0)
在循环中执行查询,而不是在结尾
$startDate='2011-08-10';
$endDate='2011-10-23';
for ($i = strtotime($startDate); $i <= strtotime($endDate); $i = strtotime('+1 day', $i)) {
if (date('N', $i) == 1){
$query = "INSERT INTO class(Day, Date) VALUES('Monday','".date('Y-m-d', $i)."')";
mysql_query($query); // you execute the query here otherwise it will overwrite over and over and only the last query will be executed
}
}
或批量
$startDate='2011-08-10';
$endDate='2011-10-23';
$query = "INSERT INTO class(Day, Date) VALUES ";
for ($i = strtotime($startDate); $i <= strtotime($endDate); $i = strtotime('+1 day', $i)) {
if (date('N', $i) == 1){
$query .= "('Monday','".date('Y-m-d', $i)."'),";
}
}
$query = substr($query, 0, -1).";"; // remove the last "," and add ;
mysql_query($query);