tags:

views:

375

answers:

4

hey can some one tell me query using php mysql that how to add date and time when a person logged in and logged out inside a database table.

+2  A: 

To keep track of the last logging-in and logging-out, you need to add two datetime fields in your "user" table (or any equivalent you can have) ; for instance :

  • log_in datetime
  • log_out datetime


Then, when you have a user logging-in, you update the log_in field, with a query such as this one :

update user
set log_in = NOW()
where user_id = 123

Of course, you have to use the right table name ,the right name for the "id" field, and the right user-id ;-)


Same when you detect a user logging-out, for the other field :

update user
set log_out = NOW()
where user_id = 123

(and same notes)


As a sidenote : detecting when a user logs-in is quite easy : he has to type his login/password, or something like that, and you can put the update query in the action of the form used to deal with that...

But detecting logging-out is not as easy : if the user clicks on some "log-out" link, of course, it's easy -- but if the user just closes his browser (or leaves its computer turned on, but just leaves), you don't have any "log-out" action...

Pascal MARTIN
A: 

You can save the time with an SQL query. Say that you have a column called "last_login" which is of the DATETIME datatype. Then you do this when the user logs in:

<?php
$userid = 1337; //This is an example ID
$query = "UPDATE users SET last_login = NOW() WHERE user_id = $userid;";
mysql_query($query) or die('Error in MySQL query. Here is the error message: '.mysql_error());
?>

Note that it's really hard to know when a user logs out. Most users just leave the page without logging out. You could have a field called "last_activity" that you update every time the user does something on the page, and count them as logged out when it's been five minutes since the last recorded activity.

Emil Vikström
A: 

You cannot do it so easy.
You should use session_set_save_handler feature.

hsz
A: 

It is not easy to detect when the user logs out (close browser or restart the computer)

The solution could be add a last activity field/table to update last activity (page load/request data/view main page) of the user by adding this update on top of all files,

Finally you want to know when the user logs out (or when was the user's last activity) that you can find from the last activity field/table.

<?php
$userid = ....; 
$query = "UPDATE users SET last_activity = NOW() WHERE user_id = $userid;";
mysql_query($query) or die('Error in MySQL query : '.mysql_error());
.
. your code here
.
?>
amir beygi