'Fatal error: Uncaught Error: Attempt to modify property "user_id" on null in

I'm trying to figure out what's going on with my userspice 3.2 installation, and unfortunately their forum is closed and there doesn't seem to be anywhere else to get support. I followed the install instructions, got the green light that everything was set up correctly and upon returning to the index page I get:

Fatal error: Uncaught Error: Attempt to modify property "user_id" on null in /homepages/13/d904845752/htdocs/models/funcs.php:393 Stack trace: #0 /homepages/13/d904845752/htdocs/models/top-nav.php(69): isUserLoggedIn() #1 /homepages/13/d904845752/htdocs/index.php(21): require_once('/homepages/13/d...') #2 {main} thrown in /homepages/13/d904845752/htdocs/models/funcs.php on line 393

The code in question is:

function isUserLoggedIn()
{
    global $loggedInUser, $mysqli, $db_table_prefix;
    $stmt = $mysqli->prepare("SELECT
        id,
        password
        FROM " . $db_table_prefix . "users
        WHERE
        id = ?
        AND
        password = ?
        AND
        active = 1
        LIMIT 1");
    $stmt->bind_param("is", $loggedInUser->user_id, $loggedInUser->hash_pw);
    $stmt->execute();
    $stmt->store_result();
    $num_returns = $stmt->num_rows;
    $stmt->close();

    if ($loggedInUser == NULL) {
        return false;
    } else {
        if ($num_returns > 0) {
            return true;
        } else {
            destroySession("userCakeUser");
            return false;
        }
    }
}

The line it's mad about is:

$stmt->bind_param("is", $loggedInUser->user_id, $loggedInUser->hash_pw);

Unfortunately I'm not comfortable enough with OOP to understand what's going on here.

php


Solution 1:[1]

The error is very clear. The variable $loggedInUser is NULL and it's not an object. You can't access a property of a non-object.

//                      VVV - NULL   VV - trying to access property
$stmt->bind_param("is", $loggedInUser->user_id, $loggedInUser->hash_pw);

To fix the problem, you should return early from the function when the variable is NULL.

function isUserLoggedIn()
{
    global $loggedInUser, $mysqli, $db_table_prefix;
    // Return early if null
    if ($loggedInUser === NULL) {
        return false;
    }

    $stmt = $mysqli->prepare("SELECT
        id,
        password
        FROM " . $db_table_prefix . "users
        WHERE
        id = ?
        AND
        password = ?
        AND
        active = 1
        LIMIT 1");
    $stmt->bind_param("is", $loggedInUser->user_id, $loggedInUser->hash_pw);
    $stmt->execute();
    $stmt->store_result();
    $num_returns = $stmt->num_rows;

    if ($num_returns > 0) {
        return true;
    }

    destroySession("userCakeUser");
    return false;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dharman