目前,我的数据库中有一个表来存储与每个用户相关的信息,每行代表一个用户。我希望在其中添加两列,一列存储用户登录的最近时间,另一列存储该用户注销的最近时间。
-
由于我对MySQL和PHP比较陌生,我想知道在MySQL中存储当前时间最简单的方法是什么?每次用户登录或注销时,我都想用当前时间更新相应的登录/注销时间列。
-
我可以使用问题1中描述的方法比较这两个时间戳吗?我想比较上次登录时间和上次注销时间,以确定用户当前是否登录。
谢谢。
您应该将列类型设置为datetime
,并在用户登录/注销时使用NOW()函数更新这些列:
update users set login_datetime = now() where user_id = :userId
update users set logout_datetime = now() where user_id = :userId
在PHP中,您可以很容易地获取这些列并进行比较,或者使用DateTime对象进行任何您喜欢的操作:
$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');
虽然我不明白你为什么要使用这样的方法,但你可以比较这两个对象来检查用户是否登录:
if ($userLoggedOutAt < $userLoggedInAt) {
echo 'The user is logged in';
}
问题:使用您的方法,如果用户正在关闭浏览器,您将如何设置注销时间?