我试图弄清楚为什么我在尝试回显数据库表中的数据时收到此错误,但无法准确地看到我正在做的事情。
$query = "SELECT * from web_projects"; // Select all rows from web_projects table
$result = mysqli_query ($con,$query);
while ($row = mysqli_fetch_array ($result)) {
foreach($row as $web) {
echo "<p>Name: ".$web->name."</p>";
echo "<p>Technologies: ".$web->tech."</p>";
echo "<p>Description: ".$web->description."</p>";
}
}
表中只有一行,但在编译时我得到了这个:
注意:尝试获取非对象的属性 /Users/leecollings/Sites/leecollings.co/index.php在第31行名称:
注意:尝试获取非对象的属性 第32行/Users/leecollings/Sites/leecollings.co/index.php
等
我是否明显错过了一些东西?
答案 0 :(得分:3)
我会删除foreach
行,并使用数组访问:
$query = "SELECT * from web_projects"; // Select all rows from web_projects table
$result = mysqli_query ($con,$query);
while ($row = mysqli_fetch_array ($result)) {
echo "<p>Name: ".$row['name']."</p>";
echo "<p>Technologies: ".$row['tech']."</p>";
echo "<p>Description: ".$row['description']."</p>";
}
答案 1 :(得分:2)
错误信息非常明确:$ web不是对象。更全面地阅读本手册: mysqli_fetch_array()返回数组或 NULL ,而非对象。
答案 2 :(得分:1)
您正在获取数组,但您正在尝试回显对象。请改用:
echo "<p>Name: ".$web['name']."</p>";
完整编辑的代码:
$query = "SELECT * from web_projects"; // Select all rows from web_projects table
$result = mysqli_query ($con,$query);
while ($row = mysqli_fetch_array ($result)) {
echo "<p>Name: ".$row['name']."</p>";
echo "<p>Technologies: ".$row['tech']."</p>";
echo "<p>Description: ".$row['description']."</p>";
}