I have a table sessions with columns (name
, start
, end
, key
and active
). Every 5 minutes I execute a PHP script running a commandline application which outputs an array.
array(
[0]
[name] => user1
[key] => h2r92
....
....
[1] ...
)
Now I would like to achieve
1) Match PHP array name
and key
with database. If the user and key exists do nothing (the session is alive). If an array item is not in the database, create a new row (new session)
2) For every session in the database that is not matched with the php array set end to current time and set active to 0 (session closed)
What is the best way to approach this?
Currently I have this code:
// get active sessions from db
$db_sessions = array();
$query = "SELECT * FROM lm_session WHERE feature_id = :fid AND active = 1";
$stmt = $this->db->prepare($query);
$stmt->execute(array(':fid' => $fid));
while($row = $stmt->fetch(PDO::FETCH_ASSOC, PDO::CURSOR_SCROLL))
{
$db_sessions[$row['key']] = $row['user'];
}
// loop through current sessions
if(is_array($data['session'])){
// New and existing sessions
foreach($data['session'] as $session) {
if(isset($db_sessions[$session['key']]) && $db_sessions[$session['key']] == $session['user']) {
unset($db_sessions[$session['key']]);
} else {
// session does not exist
$query = "INSERT INTO lm_session (`feature_id`, `user`, `workstation`, `in`, `key`, `active`) VALUES (:fid, :user, :system, :in, :key, :active)";
$stmt = $this->db->prepare($query);
$stmt->execute(array(':fid' => $fid, ':user' => $session['user'], ':system' => $session['system'], ':in' => $session['time'], 'key' => $session['key'], 'active' => 1));
}
}
// closed sessions
foreach($db_sessions as $key => $user) {
$query = "UPDATE lm_session SET active = 0 WHERE feature_id = :fid AND user = :user AND `key` = :key AND active = 1";
$stmt = $this->db->prepare($query);
$stmt->execute(array('fid' => $fid, ':user' => $user, ':key' => $key));
}
}
This works but not sure this is very efficient.