1

I'm currently trying to make a navigation menu from one of my columns in my mysql table.

Okay, so in my PHP class Database file, I have this function:

public function get_food_type(){ 
return $this->query("SELECT food_type FROM menu");
} 

And in the other file I have the following code:

<?php

require_once('Includes/wzDB.php');

$content = "<div id=\"menu\">"
. "< nav id=\"food\" >"
. "< ul >" 
. $type=wzDB::getInstance()->get_food_type();
     print($type);
      if($type->num_rows>0){
        while($row = $type->fetch_assoc()){
           echo "< li >" . htmlspecialchars($row['food_type']) . "< /li >";
        }
      } 

  "< /ul >"
. "< /nav >"
. "< /div>";

But when I try to run the file, I get the following error message

Catchable fatal error: Object of class mysqli_result could not be converted to string in C:\xampp\new_directory\htdocs\Wu_Zen2\menu.php on line 8

How do I fix this error?

chris85
  • 23,846
  • 7
  • 34
  • 51
CFl
  • 48
  • 4

2 Answers2

3

The mysqli_query() returns an object resource to your $result variable so it isn't a string.

You need to loop through it and then access the records using mysqli_fetch_assoc():

$content = "<div id=\"menu\">"
...
while ($row = mysqli_fetch_assoc($result)) {
    $content .= "<li>" . htmlspecialchars($row['food_type']) . "</li>";
}
...
$content .= "</ul>"

Don't forget to use $content .= "</ul>" after your loop to terminate the $content string.

Before using the $result variable you should use $row = mysql_fetch_array($result) or mysqli_fetch_assoc() like above.

$row = mysql_fetch_array($result);

gotnull
  • 26,454
  • 22
  • 137
  • 203
1

You are attempting to concatenate the return of get_food_type() to string $content.

To fix you need to terminate the $content string, then in the while loop you can add to the $content variable (using .=).

$content = "<div id=\"menu\">"
. "< nav id=\"food\" >"
. "< ul >";
$type=wzDB::getInstance()->get_food_type();
print($type);
if($type->num_rows>0){
    while($row = $type->fetch_assoc()){
       $content .= "< li >" . htmlspecialchars($row['food_type']) . "< /li >";
    }
} 
$content .= "< /ul >"
. "< /nav >"
. "< /div>";
Tristan
  • 3,301
  • 8
  • 22
  • 27