-3

I'm trying to figure out why I'm receiving this error when trying to echo data from a database table, but can't exactly see what I'm doing.

$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>";
}
}

Theres only one row in the table, but when compiled I'm getting this:

Notice: Trying to get property of non-object in /Users/leecollings/Sites/leecollings.co/index.php on line 31 Name:

Notice: Trying to get property of non-object in /Users/leecollings/Sites/leecollings.co/index.php on line 32

etc

Have I missed something glaringly obviously?

Lee
  • 4,187
  • 6
  • 25
  • 71
  • 5
    You are fetching an *array*, not an object. Use the `$array['syntax']`, not the `$object->syntax`. You're also already looping through the array, the `$web` variable simply isn't an object. – deceze Sep 12 '14 at 08:19
  • You should remove the mysql tag here. Your problem is just about php. – Logar Sep 12 '14 at 08:20
  • 1
    `var_dump($row)`, `var_dump($web)` to see what you're working with. – deceze Sep 12 '14 at 08:22
  • @deceze Ok, so I changed to $web['name'] etc but I'm now getting Warning: Illegal string offset 'name', for all three items. Have I done that right? – Lee Sep 12 '14 at 08:22
  • Remove foreach. And use $row instead of $web – Khushboo Sep 12 '14 at 08:23
  • possible duplicate of [PHP Arrays - Trying to get property of non-object](http://stackoverflow.com/questions/5616776/php-arrays-trying-to-get-property-of-non-object) – fdehanne Sep 12 '14 at 08:27

3 Answers3

3

I would remove foreach line, and use array accessing:

$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>";
}
lpg
  • 4,897
  • 1
  • 16
  • 16
2

Error message is very clear: $web is not object. Read the manual more thoroughly: mysqli_fetch_array() returns array or NULL, not object.

Andrey Chul
  • 136
  • 11
1

You are fetching an array, but you are trying to echo an object. Use this instead:

echo "<p>Name: ".$web['name']."</p>";

Full edited code:

$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>";
}
Luka Krajnc
  • 915
  • 1
  • 7
  • 21