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

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.

  • 写回答

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?

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

报告相同问题?

悬赏问题

  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?