2011-02-17 131 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.';