bubble_chart StackLab

User Sessions

8 steps · pending Not started · person_outline Guest
arrow_back Back

hasActiveUserSession($pdo, $user_id)

Purpose: Checks whether a given user currently has an open session.

code php
function hasActiveUserSession($pdo, $user_id)
{
    $stmt = $pdo->prepare("
        SELECT session_id
        FROM user_sessions
        WHERE user_id = :user_id
        AND session_end IS NULL
        LIMIT 1
    ");

    $stmt->execute([
        'user_id' => $user_id
    ]);

    return (bool) $stmt->fetchColumn();
}
Step by step:
  1. Prepares a SELECT for a session_id where:
  2. user_id matches session_end IS NULL (i.e. the session hasn't been closed) LIMIT 1 — only need to know if at least one exists.
  3. Executes with the given user_id.
  4. Fetches a single column and casts it to bool:
A returned session_id → true No row → false In short: Returns true if the user has a session that hasn't been ended, otherwise false. This is useful for enforcing "one active session per user" policies.

login Sign in to save your progress permanently. info Progress is saved in your browser session
format_list_numbered Step 6 of 8