【问题标题】:PHP / MySQL query - if current time/date is in schedulePHP / MySQL 查询 - 如果当前时间/日期在计划中
【发布时间】:2012-04-05 18:21:19
【问题描述】:

我正在尝试开发一个简单的基于 php 的时间表...

这是我的数据库表:

假设当前时间/日期是:2012-03-21 02:00:00

PHP 脚本应回显:Meeting 2

我有一部分脚本,但不知道接下来要做什么

<?php
$con = mysql_connect("localhost","root","");
if (!$con){die('Could not connect: ' . mysql_error());}
mysql_select_db("schedule", $con);

$current_time = date("Y-m-d H:i:s");

$result = mysql_query("SELECT * FROM events");

while($row = mysql_fetch_array($result)){

  echo $row['Subject'];
}
mysql_close($con);
?>

如何过滤查询,以匹配当前时间和预定主题?谢谢!

(如果 current_time 介于 StartTimeEndTime 之间 - 回显它是 Subject

【问题讨论】:

    标签: php mysql datetime calendar


    【解决方案1】:

    试试这个查询

    SELECT * FROM events WHERE NOW() BETWEEN StartTime AND EndTime
    

    【讨论】:

    • 为什么限制 1? OP 的示例只返回一个结果,因为数据集中只有一个匹配结果。
    • 完美!测试并确认!感谢您的快速响应!
    • @liquorvicar 我在问题编辑之前写了这个(或者我没有读过最后一行的问题:))。但是 ORDER BY 和 LIMIT 可以删除。你是对的
    【解决方案2】:

    试试select * from events where StartTime &lt;= NOW() and EndTime &gt;= NOW() NOW() 会给你当前在 mysql 中的时间。

    【讨论】:

      【解决方案3】:

      请尝试以下查询

      select * from events where current_time between startTime and endTime
      

      【讨论】:

        【解决方案4】:

        您的查询应该是这样的

        $result = mysql_query("SELECT * FROM events WHERE current_time between startTime and endTime);
        

        【讨论】:

          【解决方案5】:

          mysql BETWEEN 操作符可能有点用处。

          $startDate = gmdate('Y/m/d/ H:i:s','2012-03-21 02:00:00');
          $endDate   = gmdate('Y/m/d/ H:i:s','2012-03-21 02:23:59');
          
          $sql = 'select subject from events 
            where startTime between "'.gmdate("Y/m/d H:i:s", $startDate) . 
            '" and "' . gmdate("Y/m/d H:i:s", $endDate).'") ';
          

          【讨论】:

            【解决方案6】:

            首先,您必须使用 strtotime 将 StartTime 和 EndTime 转换为时间戳,以便您可以将其与当前时间进行比较(当前时间也是如此):

            http://php.net/manual/en/function.strtotime.php

            然后说如果 current_time > StartTime AND current_time

            while($row = mysql_fetch_array($result)){
              $startTime = strtotime($row['StartTime']);
              $endTime = strtotime($row['StartTime']);
              if (strtotime($current_time) > $startTime && strtotime($current_time) < $endTime
                  echo $row['Subject'];
            }
            

            【讨论】:

            • Derp,没想到先做SQL语句,哈哈。
            【解决方案7】:
            putenv("TZ=Asia/Calcutta");  // To Set TimeZone
            $now = date("Y-m-d H:i:s");
            $sql = "select * from events where '$now' between StartTime and EndTime";
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2011-04-06
              • 2011-09-14
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2012-11-13
              相关资源
              最近更新 更多