简单的MySQL回声 - "试图获得非对象的属性"

时间:2014-09-12 08:18:27

标签: php mysql

我试图弄清楚为什么我在尝试回显数据库表中的数据时收到此错误,但无法准确地看到我正在做的事情。

$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

我是否明显错过了一些东西?

3 个答案:

答案 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>";
}