PHP/Mysql Help? [SOLVED]

Posted by Glen on Nov. 28, 2010, 10:51 p.m.

Kinda confused by the online tutorials on this one.

I have a table that contains id's of entries in a given category.

Table "categories"

id | category

11 | red

9 | red

8 | red

22 | blue

5 | blue

7 | green

Let's say I use this:

$query = "SELECT id FROM categories WHERE category='red'";

$result = mysql_query($query);

I need an array that would be in this format:

$ids = array("11","9","8");

How do I do the conversion? Using the result from the selection?

I need the variable $ids to be in that format for a function I'm using but can't seem to get the 11,9, and 8 like that. Any help?

Comments

Glen 14 years ago

The output of that is only the first id with the category red. I only get 11 in return.

aeron 14 years ago

No Spectre, that will only give you the columns of $r for the first element in the mysql result. You have to repeat the mysql_fetch part for every element in the result. Easiest way of doing so is with a while loop:

$query = "SELECT id FROM categories WHERE category='red'";
$result = mysql_query($query);

$ids = array();
while($r = mysql_fetch_assoc($result))
{
  $ids[] = $r["id"];
}

print_r($ids);

It's also worth noting that I had to construct the $ids array manually. I don't think there are any shortcuts to doing this but it's a very simple technique regardless. You have to instantiate it with array(); but after that you can use the empty brackets to append all the values. Happy coding!

firestormx 14 years ago

Exactly what aeron said.

Glen 14 years ago

Thanks aeron. That worked perfectly!

Zarniwooop 14 years ago

w3schools?

Gift of Death 14 years ago

php.net? :P

Glen 14 years ago

a tutorial is not worth the advice of a person whose experienced. I can ask questions about something when a person shows me how to do something whereas tutorials are usually vague and don't respond when you ask them something. Typical responses post 8 and 9.