表从现在的日期开始

时间:2014-04-26 00:58:41

标签: php mysql

$sqlStr = "SELECT name, datescheduled 
             FROM table 
            WHERE datescheduled > NOW() 
         ORDER BY datescheduled DESC";      

我想用上面的结果回显一个表。无论MySQL表是否有当天的条目,我希望在接下来的90天内每天都有一行。我怎么能这样做?

3 个答案:

答案 0 :(得分:0)

所以你可以使用这个基本设置。我假设根据你的措辞,每行只有一个条目,但相应的调整很容易。

//Get the current date
$date = date('Y-m-d');
//Set the table header
$str = '<table><thead><tr><th>Name</th><th>Date</th></tr></thead><tbody>';
//START THE WHILE LOOP GETTING THE FETCH ASSOC
//Go through for 90 days
for ( $i = 0; $i < 90; $i++ ) {
    $str .= '<tr>';
    if ( $row['date'] == date('Y-m-d', strtotime('-'.$i.' day', $date)) {
        $str .= '<td>'.$row['name'].'</td><td>'.$row['date'].'</td>';
    } else {
        $str .= '<td></td><td></td>';
    }
    $str .= '</tr>';
}
//END WHILE LOOP NOT INCLUDED
$str .= '</table>';

echo $str;

答案 1 :(得分:0)

添加:

$query1 = mysql_query($sqlStr);

    echo "<table><tr>";
    echo "<th>Name</th><th>Date Scheduled</th>";
        while ($rows = mysql_fetch_assoc($query1)) {
            echo "<td>" .$rows['name']. "</td>";
            echo "<td>" .$rows['datescheduled']. "</td>";
            }
        echo "</tr><table>";

答案 2 :(得分:0)

  //select rows for next 90 days and read them into $rows 
  //use datescheduled as the key
  //assumes there will only be 1 row per date and datescheduled is in Y-m-d format

  $sqlStr = "SELECT name, datescheduled 
  FROM table 
  WHERE datescheduled > NOW() 
  AND datescheduled < date_add(now(),INTERVAL 90 DAY)
  ORDER BY datescheduled DESC";

  $rs = mysql_query($sqlStr);

  $rows = array();
  while($r = mysql_fetch_assoc($rs)) {
    $rows[$r['datescheduled']] = $r;
  }

  //add missing dates to $rows with name = false

  $begin = new DateTime();
  $end = new DateTime();
  $end->modify('+90 day');
  $interval = new DateInterval('P1D');
  $period = new DatePeriod($begin, $interval, $end);

  //iterate through the next 90 days
  foreach ($period as $dt) {
    $date_key = $dt->format( "Y-m-d" );

    if(!isset($rows[$date_key])) {
      //table doesn't contain a row for this date, so add it
      $rows[$date_key] = array('datescheduled' => $date_key, 'name' => false);
    }
  }

  //do something with $rows