50

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 ?

Dharman
  • 30,962
  • 25
  • 85
  • 135
anjanesh
  • 3,771
  • 7
  • 44
  • 58
  • ```if($Row['Data'] == false || is_null($Row['Data']))``` fixed it but am wondering if this is the right fix. – anjanesh Jan 10 '20 at 02:58
  • 1
    Depends on what `MySQL::query()` returns when no results were found. – Triby Jan 10 '20 at 03: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. – anjanesh Jan 10 '20 at 03:13
  • 3
    So, you should check if $Row is false first, only then try to access any other value. – Triby Jan 10 '20 at 03: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. – Henk Poley Mar 31 '20 at 14:48
  • If version 6 runs on PHP 7.4, then I don't think they would update 5.x – anjanesh Mar 31 '20 at 14:52
  • I recently got also this error message in Wordpress after upgrading to PHP 8.0. After downgrading to PHP 7.4, error message disappeared. – Peter Mar 25 '21 at 18:19

2 Answers2

75

Easy with PHP ?? null coalescing operator

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

Or you can use as such

$Row['Data'] ??= 'default value';
return $Row['Data'];
Dharman
  • 30,962
  • 25
  • 85
  • 135
dılo sürücü
  • 3,821
  • 1
  • 26
  • 28
  • 6
    For PHP versions < 7 you can also use a ternary statement: `$Row['data'] = isset($Row['data']) ? $Row['data'] : 'default';` – F. Müller Aug 15 '20 at 18:58
  • Wow, It's working... $Row['data'] = isset($Row['data']) ? $Row['data'] : 'default'; – Lisan E Nov 30 '21 at 10:41
11

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 = '';
  }...
raul dev br
  • 111
  • 2