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



大家好。我试图在创建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>

我看了很多东西,但似乎不知道该改什么。附注:我使用XAMP查看网站

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

请更正To:

<?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.
?>

尝试访问数组偏移

意味着你有一个数组,你试图访问一个不存在的项。正如瞳孔在他的回答中指出的那样,你试图访问循环外的$rowarray中的东西,这似乎不是你想要的,但严格地从技术上讲,这是一个不同于抛出错误的错误。尽管如此,这也需要修复,正如小学生所描述的那样。在循环之后,$rownull,这将抛出一个不同的错误。

你的问题抛出错误,因为$row被成功地创建为一个数组,但至少有一个列你试图用echo访问不存在。运行select *子句,因此需要通过运行

来引用表的结构。
desc product;

show create table product;

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

最新更新