2012-07-01 154 views
0

我有兩個字段PHP比較日期

competition {stateTime, endTime} 
當我插入到表我想確保我要插入它的價值不在任何行的該表 期間

表我鍵入此功能(PDO數據庫)

function isCompetitionInAnotherCompetition($startTime, $endTime) { 
     $query = "SELECT * FROM competition"; 
     $sth = $this->db->prepare($query); 
     $sth->execute(array()); 
     while ($row = $sth->fetch()) { 
      if ($startTime >= $row['startTime'] && $startTime <= $row['endTime']) 
       return true; 
      if ($endTime >= $row['startTime'] && $endTime <= $row['endTime']) 
       return true; 
     } 
     return false; 
    } 

但不工作好, 在數據庫中的每個日期是yyyy-mm-dd,例如2012-01-15

+2

的地方,爲什麼不乾脆用'BETWEEN'或'< ><= > ='的'WHERE'的SQL語句的WHERE子句,並使用輸出行數? –

+0

@AlvinWong我會試試 – Totti

+0

@AlvinWong它的作品,寫它作爲答案接受它 – Totti

回答

1

我可以建議,而不是寫一個測試存在的函數,並返回一個bool,你返回記錄,這樣你可以稍後測試是否沒有返回,但如果有的話,你可以使用它們,如果需要的話。正如Alvin Wong建議你可以在你的sql中使用BETWEEN,這樣你就能得到這樣的東西。

function getCompetitionsBetween($startTime, $endTime) {  

    $startTime = date("Y-m-d", $startTime); 
    $endTome = date("Y-m-d", $startTime); 

    $query = "SELECT * FROM competition 
       WHERE start_time BETWEEN ? AND ? 
       OR end_time BETWEEN ? AND ?"; 

    $sth = $this->db->prepare($query); 

    $sth->execute(array($startTime, $endTime, $startTime, $endTime)); 

    return $sth->fetchAll(); 
} 

後來/其他

$competitions = getCompetitionsBetween($startTime, $endTime); 

if (empty(competitions)) { 
    $this->save(); 
} else { 
    echo ('sorry the following competitions conflict with these dates'); 
    foreach($competitions as $k => $v) { 
     echo ($k . ':' . $v); 
    } 
}