【问题标题】:How do I get the result from a MySQL DATEDIFF query as a variable to pass to a PHP function?如何将 MySQL DATEDIFF 查询的结果作为变量传递给 PHP 函数?
【发布时间】:2012-08-12 21:30:00
【问题描述】:

我正在尝试获取表“用户”中“上次访问”列中的日期/时间与特定用户的当前日期/时间之间的秒数差异。我认为以下查询应该这样做:

$query ="SELECT unix_timestamp(NOW()) - unix_timestamp(last_visit) from users WHERE username='$user'";
$result=mysql_query($query) or die(mysql_error());

但是,我不确定如何从中获取结果作为变量,以便将其传递给 PHP 函数。有人可以帮忙吗?

【问题讨论】:

  • 您是否使用var_dump 查看过$result变量?另外,请不要使用 mysql_* 方法,那里已弃用。

标签: php mysql variables datediff


【解决方案1】:

返回带有名称的结果:

$query ="SELECT unix_timestamp(NOW()) - unix_timestamp(last_visit) AS time_diff from users WHERE username='$user'";
$result=mysql_query($query) or die(mysql_error());

while($row=mysql_fetch_assoc($result)) 
{ 
 $diff= $row['time_diff']
}

【讨论】:

    【解决方案2】:
    $query ="SELECT unix_timestamp(NOW()) - unix_timestamp(last_visit) AS time_difference from users WHERE username='$user'";
                                                                       ^
    

    我想如果这个变量有一个合适的名字,使用起来会更容易。

    【讨论】:

    • 谢谢。然后如何将'time_difference'传递给我的'time_since'函数,如$visited = time_since (*SECONDS NEED TO GO HERE*);
    • c 2上面的评论告诉了如何从查询结果中读取数据。
    • @Tim:总是链接。上面或下面的内容会有所不同,因为这个网站有时更喜欢你的答案,而不是另一个。欢迎来到 SO!
    猜你喜欢
    • 1970-01-01
    • 2020-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-30
    • 2016-07-02
    相关资源
    最近更新 更多