Skip to content
Advertisement

How to fetch indices and names from the MySQL database?

I’m working on a website and it has a category dropdown. So my database has tabled called “category”, and it has four items in there:

JavaScript

And I’m trying to get all this info into an array, so I can use it in my HTML. But I’m getting a conversion error when I try this:

JavaScript

The error I’m getting is:

JavaScript

Line 35 is where the echo statement is. So when I researched, the suggested solution was to use print_r and var_dump but both didn’t work in my case, and it just showed the same error message. What am I doing wrong here?

Advertisement

Answer

So the reason is that a variable that is on that line is being converted to a string for the purposes of echo. The only variables on that line are $id and $name.

Since id is the array key to name it’s not likely to be that!

That leaves us with $name:

  • The way you’re getting the data means you’re returning an array OF arrays…

  • Which means each $name will be an array in the format:

    JavaScript
  • …i.e. not in the format it looks as though you’re assuming.

  • With multiple results $categories will look something like:

    JavaScript
  • Notice that the index you’re using as $id is actually the array key and not the id from the query? ($name then is the sub array)

Code

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement