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();
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 :
Check $guest value (quick) :
foreach((array)$result as $guests)
{
if (!is_array($guests)) {
continue;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With