dongmieqiao3152
2016-04-16 07:55
浏览 39
已采纳

MySQL和PHP存储并比较时间戳

Currently I have a table in my database to store information related to each user, with each row represents a user. I hope to add two columns to it, one stores the most recent time when the user logs in, the other stores the most recent time when the user logs out.

  1. As I'm relatively new to MySQL and PHP, I wonder what's the easiest way to store the current time in MySQL? Every time when a user logs in or logs out, I want to update the corresponding login/logout time column with the current time.

  2. Can I compare the two timestamps using the method describe in question 1? I want to compare the last log in time with the last log out time in order to determine whether a user is currently logged in or not.

Thank you.

图片转代码服务由CSDN问答提供 功能建议

目前我的数据库中有一个表来存储与每个用户相关的信息,每行代表一个用户。 我希望为它添加两列,一列存储用户登录时的最近时间,另一列存储用户注销时的最近时间。

  1. 由于我对MySQL和PHP比较陌生,我想知道在MySQL中存储当前时间的最简单方法是什么? 每次用户登录或注销时,我都希望使用当前时间更新相应的登录/注销时间列。

  2. 我可以使用问题1中描述的方法比较两个时间戳吗? 我想比较上次登录时间和上次登出时间,以确定用户当前是否登录。

    谢谢。

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dtzk85937 2016-04-16 08:16
    已采纳

    You should set the columns type as datetime and update those columns with the NOW() function when the user login/logout:

    update users set login_datetime = now() where user_id = :userId
    
    update users set logout_datetime = now() where user_id = :userId
    

    In PHP you can easily take those columns and compare them or do whatever you like by using the DateTime object:

    $userLoggedInAt = new DateTime($row['login_datetime']);
    $userLoggedOutAt = new DateTime($row['logout_datetime']);
    
    $loginTime = $userLoggedOutAt->diff($userLoggedInAt);
    
    echo 'The user was logged in for ' . $loginTime->format('%i minutes');
    

    Although I don't understand why would you use such approach, you can compare these 2 objects to check if the user is logged in:

    if ($userLoggedOutAt < $userLoggedInAt) {
        echo 'The user is logged in';
    }
    

    Question: Using your approach, how would you set the logout time if the user is closing the browser?

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题