Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to access array offset on value of type null (PHP)

Tags:

php

problem resolved (in comments) i am making a project for school and i am getting this error Trying to access array offset on value of type null on this line of code

<div class="user-name"><?php echo $guests["firstName"] ?></div>

it is in this code and i retrieve the information out of a database

foreach((array)$result as $guests)
        {
    ?>
    <div class="posts-container">
        <div class="post-header">
            <div class="user-details">
                <div class="user-name"><?php echo $guests["firstName"] ?></div>
                <div class="user-email"></div>
            </div>
            <div class="time"></div>
        </div>
        <div class="post-message">
            <h3></h3>
            <p></p>
        </div>
    </div>
    <?php } ?>

people asked for the sql code and the type/structure of $result type/structure: object(mysqli_result)#2 (5) { ["current_field"]=> int(0) ["field_count"]=> int(9) ["lengths"]=> NULL ["num_rows"]=> int(5) ["type"]=> int(0) sql/database:

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "guestbook";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT id, firstName, lastName, email, title, message, URL, showEmail, Date FROM guestbook";
$result = $conn->query($sql);

$conn->close();
like image 687
Olaf van Gelder Avatar asked Jan 19 '26 16:01

Olaf van Gelder


1 Answers

You are trying to access to a null value as an array.

In your case, $guest value is null. So, accessing to $guest['something'] will throw a "Notice: Trying to access array offset on value of type null".

Two suggestions :

  1. Check $guest value (quick) :

    foreach((array)$result as $guests)
    {
        if (!is_array($guests)) {
            continue;
        }
    
  2. Check $result value (better) :

    If $result is a result of a SQL query, maybe try to add conditions to avoid NULL results. Or, use array_filter() before to remove empty values.

like image 101
Syscall Avatar answered Jan 22 '26 05:01

Syscall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!