dongtong0796 2013-03-27 15:06
浏览 87
已采纳

显示最接近当前日期和时间的结果(MySQL和PHP)

I'm trying to make a query but after hours of trying I can't seem to get it right. What I'm trying to do is showing 1 thing from a database that is closest to the currect date & time and after the current date & time.

my columns look like this:

  date         time
1364399654     15:00
1364684400     16:00
1367272800     12:00

my PHP looks like this:

$timestamp_now = strtotime(date('d-m-Y')); //Creates a timestamp of the currect date
$time_now = date('H:i');
$sql = mysql_query('SELECT * FROM table_name ORDER BY date ASC, time ASC (WHERE date > '.$timestamp_now.') AND (time > "'.$time_now.'") LIMIT 1') or die(mysql_error());
$data = mysql_fetch_array($sql);

However, this doesn't work. Any words of advice?

  • 写回答

3条回答 默认 最新

  • douao8204 2013-03-27 15:13
    关注

    I would ditch using the PHP date/time methods and rely on MySQL giving a query that looks like

    SELECT * FROM table_name 
    WHERE date > CURRENT_DATE
    OR (
        date = CURRENT_DATE
        AND 
        time > CURRENT_TIME
    )
    ORDER BY date ASC, time ASC LIMIT 1
    

    The OR makes sure that it gets the correct records else the TIME portion would block i.e. a result at 03:00 from the next day from appearing if the current time was at 06:00

    I see you are using timestamp values there so you can always still pass in the PHP date numeric in place of CURRENT_DATE. This would give a final script of

    $timestamp_now = strtotime(date('d-m-Y')); //Creates a timestamp of the currect date
    $sql = mysql_query('SELECT * FROM table_name 
                        WHERE date > '.$timestamp_now.'
                        OR (
                            date = '.$timestamp_now.'
                            AND 
                            time > CURRENT_TIME
                        )
                        ORDER BY date ASC, time ASC LIMIT 1') or die(mysql_error());
    $data = mysql_fetch_array($sql);
    

    I would advise considering changing the database if possible to store just as a MySQL DATETIME field, as then you can change this query to simply WHERE datetime > NOW(), but that's entirely up to you. Just have always found MySQL date handling more logical than PHPs.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 echarts动画效果失效的问题。官网下载的例子。
  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加