【问题标题】:Save dates for database within date range在日期范围内保存数据库的日期
【发布时间】:2011-08-15 06:13:54
【问题描述】:

我想选择日期范围内的所有星期一并将日期保存在数据库中。这是我尝试过的代码。但它只保存最后一个日期。我想保存所有的星期一。请问您能帮帮我吗?

$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)."')";
    }
}

【问题讨论】:

标签: php strtotime


【解决方案1】:

在循环中执行查询,而不是在最后执行

$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);

【讨论】:

  • mysql 支持批量插入。他们就是为此而发明的。
  • @zerkms 你是这个意思吗?
猜你喜欢
  • 1970-01-01
  • 2014-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-11
  • 1970-01-01
  • 1970-01-01
  • 2019-02-23
相关资源
最近更新 更多