Reputation: 2749
I am creating a simple web app using PHP/MySQL and I would like to display to the users something like the following;
`Last Login Time: Friday 4th of March at 2:25pm'
My users
database has the following structure;
+---------+-----------+-------------------+---------------------+
| user_id | user_name | user_email | lastLogin |
+---------+-----------+-------------------+---------------------+
| 1 | Joe | [email protected] | 0000-00-00 00:00:00 |
+---------+-----------+-------------------+---------------------+
What is the best way to approach this? Presumably I update the lastLogin
column on logout? Then on the users next login, I select this column data and display it?
My code so far is as follows;
(The logout()
function works perfectly fine if I remove the two $stmt
lines.)
class.user.php
class USER {
public function logout() {
$stmt = $this->db->prepare("UPDATE users SET lastLogin = now()");
$stmt->execute();
session_destroy();
unset($_SESSION['user_session']);
return true;
}
public function lastLogin() {
$stmt = $this->db->prepare("SELECT lastLogin FROM users WHERE user_name=:user_name");
$stmt->bindparam(":user_name", $_SESSION['user_name']);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$date = date('jS M Y h:i', strtotime($row['lastLogin']));
}
return $date;
}
}
logout.php
require_once('session.php');
require_once('class.user.php');
$user_logout = new USER();
if($user_logout->is_loggedin()!="")
{
$user_logout->redirect('index.php');
}
if(isset($_GET['logout']) && $_GET['logout']=="true")
{
$user_logout->logout();
$user_logout->redirect('index.php');
}
index.php
<?php echo '<p>Last Login ' .$USER->lastLogin();'</p>' ?>
Any help appreciated.
Upvotes: 0
Views: 903
Reputation: 57703
What is the best way to approach this? Presumably I update the lastLogin column on logout?
You can't force a user to logout so this approach wont work.
Instead of setting the lastLogin
when logging out, consider setting it on logging in. You can keep a 2nd column actualLastLogin
so avoid overwriting the value immediately.
On login, do:
UPDATE users
SET lastLogin = NOW(),
actualLastLogin = lastLogin
..
Then read the value of actualLastLogin
.
It's possible users don't have a clear login moment because you might have a system that persist a session (such as a "remember me on this computer"). In that case you need to define what you think is a session. If you're inactive for 1 hour does that mark the end of your session? It's up to you.
Alternatively you could keep a log of logins and return the last one.
Upvotes: 1