数据库与当前日期的日期比较

时间:2015-09-08 17:13:18

标签: php mysql

我已将数据以d / m / y格式存储在数据库中。如何将其与当前日期进行比较? 这是我的代码。但它不能正常工作。

<!DOCTYPE html>
<html>
<body>
 <?php
 session_start();
include_once 'dbconnect.php';

date_default_timezone_set("Asia/Dhaka");
$t=time();
 $d=date("d/m/Y");
 $bar=date("l");
 $time=date("h:i:sa");

 $result=mysql_query("SELECT * FROM seminar WHERE date >= '$d'");
 $cnt=mysql_query("SELECT COUNT(*) FROM seminar WHERE date >= '$d'");
 $find=mysql_fetch_row($cnt);
 $num=$find[0];
 while($uRow=mysql_fetch_assoc($result))
{
   echo "A Seminar on ".$uRow['about']." will be held in ".$uRow['place'] ."      at".$uRow['time'].",".$uRow['date']."<br><br>";
}
 //mysql_query("DLETE FROM seminar WHERE date < '$d'");
  ?>
  </body>
  </html>

3 个答案:

答案 0 :(得分:3)

您不需要在PHP中获取日期,您只需使用SQL:

SELECT * FROM seminar WHERE date >= CURDATE()

了解更多here

如果您的日期存储为字符串(因为您的问题似乎暗示)而不是日期,则应考虑将它们存储为日期。如果由于某种原因不能选择,你可以这样做:

SELECT * FROM seminar WHERE STR_TO_DATE(date, '%d/%m/%Y') >= CURDATE()

此外,您不应使用mysql_*函数,因为它们已被弃用且易受SQL injection attacks攻击。改为使用MySQLi或PDO。

此外,无需额外的查询来获取计数。只需检查第一个查询影响的行数。如果您使用MySQLi,请使用mysqli_affected_rows()

答案 1 :(得分:1)

 <!DOCTYPE html>
    <html>
    <body>
     <?php
     session_start();
    include_once 'dbconnect.php';

    date_default_timezone_set("Asia/Dhaka");
    $t=time();
     $d=date("d/m/Y");
     $bar=date("l");
     $time=date("h:i:sa");

     $result=mysql_query("SELECT * FROM seminar WHERE DATE_FORMAT( `date` , '%d-%m-%Y' ) <= '$d'");
     $cnt=mysql_query("SELECT COUNT(*) FROM seminar WHERE DATE_FORMAT( `date` , '%d-%m-%Y' ) >= '$d'");
     $find=mysql_fetch_row($cnt);
     $num=$find[0];
     while($uRow=mysql_fetch_assoc($result))
    {
       echo "A Seminar on ".$uRow['about']." will be held in ".$uRow['place'] ."      at".$uRow['time'].",".$uRow['date']."<br><br>";
    }
     //mysql_query("DLETE FROM seminar WHERE date < '$d'");
      ?>
    </body>
    </html>

答案 2 :(得分:0)

因为该日期格式(&#39; 01/01/2015&#39;小于&#39; 31/01/1970&#39;)

我现在无法检查,但这必须有效:

$d=date("Y-m-d");
$result=mysql_query("SELECT * FROM seminar WHERE DATE_FORMAT(date,'%Y-%m-%d') >= '$d'");
$cnt=mysql_query("SELECT COUNT(*) FROM seminar WHERE DATE_FORMAT(date,'%Y-%m-%d') >= '$d'");