简体   繁体   中英

Error - 'trying to access array offset on value of type null'

I continually get the error: 'trying to access array offset on value of type null' at the lines where my session variables are defined. I have looked around the web/ on stack and at my code, and I cannot figure out what is wrong, This is my first time defining session variables from two different tables in the one document/ code page. so I suspect it is something to do with that: Below is the PHP code whereby the error is occurring:

<?php

    session_start();

    include('../includes/dbh.inc.php');


    $sql = 'SELECT * FROM shelfitems';
    $lqs = 'SELECT * FROM shelfwebsites';

    $result = mysqli_query($conn, $sql);
    $result2 = mysqli_query($conn, $lqs);

    $shelfitems = mysqli_fetch_all($result, MYSQLI_ASSOC);
    $shelfwebsites = mysqli_fetch_all($result2, MYSQLI_ASSOC);
    $shelfwebsite = mysqli_fetch_assoc($result2);
    $shelfitem = mysqli_fetch_assoc($result);

    $_SESSION['parent_id'] = $shelfitem['parent_id'];
    $_SESSION['folder'] = $shelfwebsite['folder'];
    $parent_id = $_SESSION['parent_id'];
    $folder = $_SESSION['folder'];
    mysqli_close($conn);

The problem is that mysqli_fetch_assoc returns NULL. So your variables $shelfitem and $shelfwebsite are nulls

To avoid this error, you can check if there any result before fetching

if (mysqli_num_rows($result) > 0) {
    $shelfitem = mysqli_fetch_assoc($result);

    $_SESSION['parent_id'] = $shelfitem['parent_id'];
}

https://www.php.net/manual/en/mysqli-result.fetch-assoc.php https://www.php.net/manual/en/mysqli-result.num-rows.php

UPD

Reasons why result may be empty

  1. Your sql query did not find anything. Check if you tables filled
  2. You already read $result previously using mysqli_fetch_all

I can't check second reason at the moment, but you could try to comment strings and check if it will work

$shelfitems = mysqli_fetch_all($result, MYSQLI_ASSOC);
$shelfwebsites = mysqli_fetch_all($result2, MYSQLI_ASSOC);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM