bubble_chart StackLab

User Sessions

8 steps · pending Not started · person_outline Guest
arrow_back Back

startUserSession($pdo)

1. startUserSession($pdo)

Purpose: Records the start of a new user session in the database.
code php
function startUserSession($pdo)
{
    if (!isset($_SESSION['user_id'])) {
        return false;
    }

    $user_id = $_SESSION['user_id'];

    $stmt = $pdo->prepare("
        INSERT INTO user_sessions (
            user_id,
            session_start
        )
        VALUES (
            :user_id,
            NOW()
        )
    ");

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

    return $pdo->lastInsertId();
}
Step by step: 1. Guard clause – Checks whether $_SESSION['user_id'] is set. If not, the user isn't logged in, so the function returns false and does nothing. 2. Reads the user ID – Pulls $_SESSION['user_id'] into a local variable. 3. Prepares an INSERT statement – Inserts a new row into the user_sessions table with: user_id → the current user session_start → NOW() (current DB timestamp) 4. Executes the statement with the bound parameter. 5. Returns $pdo->lastInsertId() — the auto-incremented session_id of the newly created row. This ID is typically stored in $_SESSION['session_id'] by the calling code. In short: Creates a new session record in the DB and returns its ID.

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