fetchUserSessions (function)

Last updated: Fri, Apr 14, 2023 5:06 pm
Return to Knowledgebase


Retrieves user session data from the database for the currently logged-in user.




# Parameter Data Type Required Description
1 $all = false bool Yes A boolean value that specifies whether to retrieve all sessions (if true) or only active sessions (if false).

Further Documentation:

The function first sets the global variable $user, which is an instance of the User class that provides access to user-related functionality.

The function then gets an instance of the database class using the DB::getInstance() method, which creates a new PDO object and establishes a connection to the database.

If $all is false, the function executes a query to select all rows from the "us_user_sessions" table where the "UserSessionEnded" column is 0 (i.e., the session is still active) and the "fkUserID" column matches the ID of the currently logged-in user (stored in the $user global variable). The rows are ordered by the "UserSessionStarted" column, which contains the start time of each session.

If $all is true, the function executes a similar query but selects all rows from the table for the currently logged-in user, regardless of whether the session is active or not.

If the query returns one or more rows, the function returns the results as an array of objects. Each object represents a session and contains properties corresponding to the columns in the "us_user_sessions" table.

If the query returns no rows, the function returns false to indicate that no sessions were found.

Overall, this function provides a convenient way to retrieve user session data for the currently logged-in user, which can be used to track user activity and diagnose issues related to user sessions.

// Retrieve all active sessions for the current user
$sessions = fetchUserSessions();

// Display session data in a table
if ($sessions) {
echo '';
echo '';
foreach ($sessions as $session) {
echo '';
echo '';
echo '';
echo '';
echo '';
echo '
Session IDStart TimeLast Activity
} else {
echo 'No active sessions found.';