2011-02-17 129 views
0

我遇到以下问题:PHP:比较日期

我想,比较今天对阵一些日期日期在一个数据库中,然后如果尚未到期,展示一些东西...但如果表格中的所有日期都已过期,显示的内容如'此时不安排演讲,再次返回'。

至于第一件事,这是没有问题的,但我不能证明那里并没有任何未来日期的文字...

下面的代码,

表: ID,dateposted ,date_course,标题,正文

$sql = "SELECT * 
     FROM L 
     ORDER BY L.dateposted DESC;"; 
     $result = mysql_query($sql) or die(mysql_error()); 
     while($row = mysql_fetch_assoc($result)) 
     { 
      $exp_date = $row['date_course']; 
      $todays_date = date("Y-m-d"); 
      $today = strtotime($todays_date); 
      $expiration_date = strtotime($exp_date); 
      if ($expiration_date >= $today) 
      { 
       echo "<a href='courses.php'>" . $row['title']. "</a>"; 
       echo "</br>"; 
      } 
     } 
+0

你知道SQL有这个特殊的语法WHERE子句,它允许你指定你选择的标准 – 2011-02-17 20:11:28

回答

2

我会假设你正在使用MySQL。对你的查询和代码进行一些小的修改应该可以实现这个功能。你绝对应该在查询中做这种过滤,而不是代码。

$sql = "SELECT * 
    FROM L 
    WHERE date_course < NOW() AND dateposted < NOW() 
    ORDER BY L.dateposted DESC;"; 

$result = mysql_query($sql) or die(mysql_error()); 

if (mysql_num_rows($result) > 0) 
{ 
    while ($row = mysql_fetch_assoc($result)) 
    { 
     echo "<a href='courses.php'>" . $row['title']. "</a>"; 
     echo "</br>"; 
    } 
} 
else 
{ 
    echo "No results available"; 
} 
+1

这样做了!谢谢 – A3efan 2011-02-17 20:27:09

0

几种方法来做到这一点。一种方法是使查询的日期比较部分。如果未选择行,请显示您的特殊消息。

否则,你可以设置一个标志像

$has_courses = false; 
while ($row = fetch() { 
    $has_courses = true; 
    ... 
} 
if (!$has_courses) { echo 'No courses'; } 
0

虽然你可以这样做更有效的改善您的查询,这里是您所请求的具体修复:

$sql = "SELECT * 
     FROM L 
     ORDER BY L.dateposted DESC;"; 
     $result = mysql_query($sql) or die(mysql_error()); 
     $out = false; 
     while($row = mysql_fetch_assoc($result)) 
     { 
      $exp_date = $row['date_course']; 
      $todays_date = date("Y-m-d"); 
      $today = strtotime($todays_date); 
      $expiration_date = strtotime($exp_date); 
      if ($expiration_date >= $today) 
      { 
       $out = true; 
       echo "<a href='courses.php'>" . $row['title']. "</a>"; 
       echo "</br>"; 
      } 
     } 
     if (!$out) 
      echo 'Nothing found.';