Query Results to Array [Solved]

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
christh
Forum Commoner
Posts: 25
Joined: Sat Jan 16, 2010 5:27 am

Query Results to Array [Solved]

Post by christh »

Hello

I'm trying to modify a bit of php I've found, but either because it's the early hours of the morning here or I'm stupid, but I just can't get it to work - None of the examples I've found on the internet work for me either.

Basically the code I want to modify has the line

Code: Select all

$items = array(
"Car"=>"Red",
"Bike"=>"Blue");
Now, all I want to do is replace the static array with the results from my query - I thought...

Code: Select all

$result = mysql_query ("SELECT item, color FROM things");
	$items = array();
	while ($row = mysql_fetch_assoc($result)) {
	$items[] = $row;
	}
...would do the job but I'm wrong.

Can anybody help a tired amateur?

Many thanks

Chris
Last edited by christh on Mon Feb 21, 2011 3:14 am, edited 1 time in total.
danwguy
Forum Contributor
Posts: 256
Joined: Wed Nov 17, 2010 1:09 pm
Location: San Diego, CA

Re: Query Results to Array

Post by danwguy »

I would think you would have to do something more along the lines of...

Code: Select all

$items = array('$row[item']', $row[seconditem'], '$row[thirditem'], //and so on...);
either that or it's the end of the day at work and I've been so bored that I am making absolutely no sense. Not sure at this point.
User avatar
Jonah Bron
DevNet Master
Posts: 2764
Joined: Thu Mar 15, 2007 6:28 pm
Location: Redding, California

Re: Query Results to Array

Post by Jonah Bron »

Code: Select all

$result = mysql_query ("SELECT item, color FROM things");
$items = array();
while ($row = mysql_fetch_assoc($result)) {
    $items[$row['item']] = $row['color'];
}
That ought to do the trick.
amargharat
Forum Commoner
Posts: 82
Joined: Wed Sep 16, 2009 2:43 am
Location: Mumbai, India
Contact:

Re: Query Results to Array

Post by amargharat »

Code: Select all

$result = mysql_query ("SELECT item, color FROM things");
        $items = array();
        while ($row = mysql_fetch_assoc($result)) {
        $items[$row["item"]] = $row["color"];
        }
christh
Forum Commoner
Posts: 25
Joined: Sat Jan 16, 2010 5:27 am

Re: Query Results to Array

Post by christh »

Hi Guys

Many thanks for the suggestions, which worked perfectly.

Cheers

Chris
Post Reply