尝试获取 属性 的非对象在页面的一部分有效,但在其他部分无效

Trying to get property of non-object works on one part of page but not on other

我正在使用准备好的语句从我的 MySQL 数据库中检索一行,该语句可以正常工作(在 phpmyadmin 中测试),具有特定的值等

我使用 <?php echo (htmlspecialchars($row_feed->f_text)); ?> 在我页面的第 400 行和第 900 行再次显示它(这是一个实际的复制粘贴)。第一个实例按预期显示结果,第二个实例抛出错误:

Uncaught Customizable_Exception: Trying to get property 'f_text' of non-object in C:\xampp\htdocs\bbto.eu\index.php:878

这怎么可能?我已经检查过,$row_feed 变量没有被重用于介于两者之间的其他东西,并且它在前面几行的同一个文件中工作正常。唯一的问题是第一个实例在这个循环中 while($row_feed = $feed->fetch_object()) { } 而另一个实例在它关闭之后但是从什么时候开始有任何影响?

最小可重现示例:

$sql = "SELECT * FROM feed";
$statement = $mysqli->prepare($sql);
if(!$statement->execute()) { die("Query error: ".$statement->error); } 
$feed = $statement->get_result();

while ($row_feed = $feed->fetch_object()) {
echo (htmlspecialchars($row_feed->f_text));
}
### other stuff going on
echo (htmlspecialchars($row_feed->f_text));

我在第二次回显时收到错误消息。

The only thing is that the first instance is within this loop while($row_feed = $feed->fetch_object()) { } while the other one is after it closes but since when has that any impact?

对查询结果进行这种 while 循环的基本原理是,当没有更多记录要处理时,fetch 调用将 return NULL,这就是使循环在此时终止。所以当然在你的循环之后,$row_feed 是 NULL。

how can I reuse $row_feed's last value

将其存储到另一个变量中, while 循环中:$last_row = $row_feed;。这将在每次循环迭代中被覆盖,因此只有最后一个值在循环后“存活”。因为它是 inside 循环,当 $row_feed = $feed->fetch_object() 导致 NULL 时,该行将不再执行。

while ($row_feed = $feed->fetch_object()) {
  echo htmlspecialchars($row_feed->f_text);
  $last_row = $row_feed;
}
### other stuff going on
echo htmlspecialchars($last_row);