简体   繁体   English

如何使用MySQL和PHP在每次登录时将用户的注销时间存储在数据库中?

[英]how to store logout time of user in database for each login using MySQL and PHP?

I'm new to PHP and MySQL. 我是PHP和MySQL的新手。 My project is about a school management system. 我的项目是关于学校管理系统的。 In this project I have 3 users. 在这个项目中,我有3个用户。 Whenever they login, the login time is stored correctly each time. 每当他们登录时,每次登录时间都会正确存储。 And when a user logs out , the log out time is stored. 当用户注销时,将存储注销时间。 The problem is, the last logged out time is also updated to the previous log out times for that particular user. 问题是,该特定用户的上次注销时间也被更新为以前的注销时间。 Thank You in advance 先感谢您

My code is: 我的代码是:

login.php login.php

$sql = $conn->query("Insert into userlog (username) values ('$username')");

Log out. 登出。 php 的PHP

<?php

include("php/dbconnect.php");
ob_start();


mysqli_query($conn,"UPDATE userlog SET logoutTime = NOW()  WHERE username = '$_SESSION[username]'   ");


unset($_SESSION['name']);

unset($_SESSION['uid']);

unset($_SESSION['username']);

echo '<script type="text/javascript">window.location="login.php"; </script>';


?>

I expect , 我预计 ,

id username login logout
1    1111   12:10  12:20
2    1111   12:40  12:50

But my output is like below, 但是我的输出如下

id username login logout
1    1111   12:10  12:50
2    1111   12:40  12:50

You need to make sure you only update the latest login time, so add a condition to your WHERE clause to that effect: 您需要确保仅更新最新的登录时间,因此可以在WHERE子句中添加一个条件:

mysqli_query($conn,"UPDATE userlog 
                    SET logoutTime = NOW()  
                    WHERE username = '$_SESSION[username]'
                      AND loginTime = (SELECT maxLoginTime 
                                       FROM (SELECT MAX(loginTime) AS maxLoginTime
                                             FROM userlog 
                                             WHERE username = '$_SESSION[username]') u)"
            );

Demo on dbfiddle dbfiddle上的演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM