尝试访问 null 类型值的数组偏移量但找不到正确的解决方案

Trying to access array offset on value of type null but can't find the right solution

美好的一天。我试图在创建 Web 购物车方面取得进展,但我被困在 尝试访问数组偏移量 上。我可以删除它,这样它就不会显示,但我需要 SQL 数据库中的文本。

<?php

$sql = "SELECT * from product";
$result = mysqli_query($conn, $sql);
  while($row = mysqli_fetch_assoc($result)) {
    echo $row['id'] ." ". $row['name'] ." ". $row['image'] ." ". $row['price'] ." ". $row['description'] ." ". $row['type']. "<br>";
  } //This part is showing up without a problem
?>

<div class="col-md-3">
  <img src="<?php echo $row['image']?>" alt="">
  <h3><?php echo $row['name']?></h3>
  <h6><?php echo $row['price']?></h6> //This part however is showing me Notice: Trying to access array offset on value of type null in Line 45,46,47
</div>

我浏览了很多东西,但似乎无法掌握要更改的内容。 P.S。 - 我正在使用 XAMP 浏览网站

实际上,您正在循环中获取 $row 的值,并且在打印所有值之前循环正在关闭。

请更正为:

<?php

$sql = "SELECT * from product";
$result = mysqli_query($conn, $sql);
  while($row = mysqli_fetch_assoc($result)) {
    echo $row['id'] ." ". $row['name'] ." ". $row['image'] ." ". $row['price'] ." ". $row['description'] ." ". $row['type']. "<br>";
// `$row` was closing here, it shouldn't close here as its values are accessed below it.
?>

<div class="col-md-3">
  <img src="<?php echo $row['image']?>" alt="">
  <h3><?php echo $row['name']?></h3>
  <h6><?php
  } // This needs to be moved here.
?>

Trying to access array offset

表示您有一个数组,您在其中尝试访问不存在的项目。正如 Pupil 在他的回答中指出的那样,您尝试在循环外访问 $row array 中的内容,这似乎不是您想要的,但严格来说,从技术上讲,这是一个不同于抛出错误。尽管如此,正如 Pupil 所描述的,这也需要修复。循环后 $rownull,这将引发不同的错误。

您的问题引发错误,因为 $row 已成功创建为数组,但您尝试使用 echo 访问的列中至少有一个不存在。您 运行 一个 select * 子句,因此您需要通过 运行ning

引用 table 的结构
desc product;

show create table product;

并查看列名是什么,查看列名是否与您尝试以区分大小写的方式在 PHP 中引用的列名相匹配。