doujiexi1824 2014-10-04 18:51
浏览 13
已采纳

PHP查询时间()表单mysql

I want that my PHP checks if the time in the mysql db is the same, and if not that it will be changed.

This is what I got:

<?php
$last_time_check=mysqli_query($con,"SELECT `time` FROM `servervars`");
if((time()-$last_time_check) >=1)
{
   mysqli_query($con, 'UPDATE `servervars` SET `time`='.$time.' WHERE ID=1');
}
?>

$con is the connection to the DB.
Current value 'time' in servervars: 1412448339
Value 'ID' is 1

I do something wrong, but I just cannot find where it's going wrong.

The Fix

I've removed the variable $last_time_check and only checked if the time could get changed. If this happends then it will send another message to the client.

mysqli_query($con, 'UPDATE `servervars` SET `time` = UNIX_TIMESTAMP() WHERE ID = 1 AND UNIX_TIMESTAMP() - `time` >= 1');
    if ($con->affected_rows)
    {
        // at least 1 second has elapsed, do stuff
    }
  • 写回答

1条回答 默认 最新

  • dongpo2014 2014-10-04 18:53
    关注

    MySQL has an equivalent to time(), its the function UNIX_TIMESTAMP(). Differently though, it can take a DATETIME as parameter to convert it into UNIX time, but when used without parameters its the same as UNIX_TIMESTAMP(NOW()).

    UPDATE servervars SET time = UNIX_TIMESTAMP() WHERE ID = 1
    

    Update

    Ok so about the other issues. You are doing it all wrong. mysqli_query does not return the value directly. To fetch the value of time from the database, you need 3 steps:

    $result = $con->query('SELECT `time` FROM `servervars` WHERE ID = 1'); // fetch result set
    $row    = $result->fetch_row(); // fetch a row from the result set, as an array
    $last   = $row[0]; // get the first element from the row you just fetched
    

    Notice $con->query() can fail if theres a problem with the connection, the database, the table, or the query syntax itself, and $result->fetch_row() can fail if there are no results for the query. You should validate them before proceeding to the next step.

    Alternatively, you can do this:

    $con->query('UPDATE `servervars` SET `time` = UNIX_TIMESTAMP() WHERE ID = 1 AND UNIX_TIMESTAMP() - `time` >= 1');
    if ($con->affected_rows)
    {
        // at least 1 second has elapsed, do stuff
    }
    

    This way we shortened your solution to a single query, that updates the field if necessary and report back that it happened or not..

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)