PHP MySQL日期比较

时间:2011-09-17 21:32:49

标签: php mysql date

我有一个包含Data1,data2,data3 ...... Data7的Mysql,我希望与当前日期进行比较,在网上搜索我到目前为止:

$curDate = date("Y-m-d");
$query = "SELECT Id FROM Programacao where Data1 = $curDate";
$result = mysql_query($query);   
if(!$result) {echo 'Nada';}
while ($row = mysql_fetch_array($result))
{
     echo "Id = ".$row ['Id'];
}

但是我只能阅读第一个,是否可以同时比较所有这些?

2 个答案:

答案 0 :(得分:1)

SELECT Id,CASE 
    WHEN  Data1 = CURDATE() then 'Data1'
    WHEN  Data2 = CURDATE() then 'Data2'
    WHEN  Data3 = CURDATE() then 'Data3'
    ELSE ''
END as Data_Table
FROM Programacao
WHERE Data1 = CURDATE()
   OR Data2 = CURDATE()
   OR Data3 = CURDATE()
....

答案 1 :(得分:1)

您应该使用逻辑运算符。如果您需要检查Data中至少有一个是$curDate

$query = "
SELECT Id 
FROM Programacao 
WHERE Data1 = $curDate 
   OR Data2 = $curDate
   OR Data3 = $otherDateIfYouNeedOther
";

如果您需要检查所有内容是否正常,则应将or替换为and

此外,据我记得你应该在引号中使用Date值,所以正确的是

$query = "
SELECT Id 
FROM Programacao
WHERE Data1 = '$curDate'
   OR Data2 = '$curDate'
   OR Data3 = '$otherDateIfYouNeedOtherOrSameOtherwise'
";