57

I just upgraded my server's PHP version to PHP 7.4.1 and now getting this error:

Notice: Trying to access array offset on value of type bool in

public static function read($id)
{
    $Row = MySQL::query("SELECT `Data` FROM `cb_sessions` WHERE `SessionID` = '$id'", TRUE);
    
    # http://php.net/manual/en/function.session-start.php#120589
    //check to see if $session_data is null before returning (CRITICAL)
    if(is_null($Row['Data']))
    {
        $session_data = '';
    }
    else
    {
        $session_data = $Row['Data'];
    }
    
    return $session_data;
}

What is the fix for PHP 7.4 ?

8
  • if($Row['Data'] == false || is_null($Row['Data'])) fixed it but am wondering if this is the right fix. Commented Jan 10, 2020 at 2:58
  • 1
    Depends on what MySQL::query() returns when no results were found. Commented Jan 10, 2020 at 3:01
  • If no results are found then it returns false , if there is a result then it returns the first row as an assoc array, public static function query($sql, $returnRow = FALSE) - the 2nd parameter is TRUE in this case. Commented Jan 10, 2020 at 3:13
  • 4
    So, you should check if $Row is false first, only then try to access any other value. Commented Jan 10, 2020 at 3:15
  • 1
    Just a heads up, Collection from at least Laravel 5.4 - 5.8 are incompatible with PHP 7.4, and crashes with this error. Commented Mar 31, 2020 at 14:48

2 Answers 2

87

Easy with PHP ?? null coalescing operator

return $Row['Data'] ?? 'default value';

Or you can use as such

$Row['Data'] ??= 'default value';
return $Row['Data'];
Sign up to request clarification or add additional context in comments.

2 Comments

For PHP versions < 7 you can also use a ternary statement: $Row['data'] = isset($Row['data']) ? $Row['data'] : 'default';
Wow, It's working... $Row['data'] = isset($Row['data']) ? $Row['data'] : 'default';
13

If your query does not return a row, then your variable $Row will be filled with false, so you can test if the variable has a value before try to access any index inside it:

if($Row){
  if(is_null($Row['Data']))
  {
      $session_data = '';
  }...

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.