dongzhizhai4070 2017-05-25 17:05 采纳率: 0%
浏览 26
已采纳

PHP / mySQL获得x秒的时差

My goal is to get the time difference between 2 different times, one from my database, and one from the client's PHP timestamp, and compare them. Then, if the time difference is less than or equal to 10 seconds, then do something.

My code, which does not work, is as follows.

date_default_timezone_set('America/Chicago');
$timestamp = date('Y-m-d H:i:s');

$sqlcheck = $dbh->prepare("SELECT timestem FROM mytable WHERE UNIX_TIMESTAMP(timestem) - UNIX_TIMESTAMP('".$timestamp."') <= 10");
$sqlcheck->execute();
    if ($sqlcheck === ''){
        echo "Yes";
    }
    else {
        echo "No";
    } 

timestem is a DATETIME value from mySQL. $sqlcheck is meant to portray the result of the query. If the query returns nothing, then echo Yes. If it returns something from my query, then echo No.

Without getting too convoluted in explanation, my end-goal is to check how long it has been since a database operation before a client is allowed to perform updates.

  • 写回答

2条回答 默认 最新

  • duankang8114 2017-05-25 17:25
    关注

    You should use the MySQL built-in TIMESTAMPDIFF function:

    $sqlcheck = $dbh->prepare('SELECT timestem FROM mytable WHERE TIMESTAMPDIFF(SECOND, timestem, $1) <= 10');
    $result = $sqlcheck->execute([$timestamp]);
    

    Note that instead of concatenating strings, I am providing the $timestamp as a parameterized argument.

    To check the result, you can't just check for string equality. Instead, use fetchColumn on the result object:

    if ($timestem = $result->fetchColumn()) {
        echo "YES";
        // You can also use the value of `$timestem` here.
    } else {
        echo "NO";
    }
    

    Note that this assumes there is only one row. For multiple rows, you need a loop. Note that only rows that match the condition are returned, so you will never see any NO output if you use a loop.

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

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 MATLAB动图问题
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名