0

I want to select all the Mondays within date range and save the dates in the database. This is the code I tried. But it save only last date. I want to save all the Mondays. Please can you help me?

$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)."')";
    }
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Nisha
  • 385
  • 2
  • 3
  • 5

1 Answers1

0

execute the query in the loop, and not at the end

$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
    }
}

or bulk

$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);
Mihai Iorga
  • 39,330
  • 16
  • 106
  • 107