Hello all,

While attempting to switch from a hard-coded array to a dynamic array read from a db table, I'm running into a few snags.

I'm using the following function to create the dropdown menu, and it has worked for everything thus far:

//
function showDrop($array, $active, $echo=true){
	$string = '';
	foreach($array as $k => $v){
		$s = ($active == $k)? ' selected="selected"' : '';
		$string .= '<option value="'.$k.'"'.$s.'>'.$v.'</option>'."\n";     
	}
        if($echo)   echo $string;
	else        return $string;
}

...send in the array, prints out a menu. No problem.

But when I try to create the same array dynamically, I can't get it to work.

I'm sure I'm missing something simple, but I've been looking at this too long to see it clearly.

Ideally, I'd like to create the following array:

$my_arr = array('4'=>"Apple",
		      '3'=>"Banana",
		      '2'=>"Orange",
		      '5'=>"Plum");

The table is a simple id/name setup.

The following code I've been trying to get to work to populate and create a similar array:

function setupCategories(){
	include "dbConnect.php";
	$sql = "SELECT * FROM Categories ORDER BY name";
	$result = mysql_query($sql);
	$my_arr = array();
	while($rows = mysql_fetch_array($result)){ 
		$id = $rows['id']; 
		$name = $rows['name']; 
		$my_arr[] .= [$id][$name];
	}
}
setupCategories();

This should be an easy fix, but I'm just not seeing it....any input is much appreciated.

Thanks,
Jeff

Recommended Answers

All 3 Replies

Member Avatar for Rkeast

You are adding the values to the array incorrectly.

Do it like this:

...
	while($rows = mysql_fetch_array($result)){ 
		$id = $rows['id']; 
		$name = $rows['name']; 
		$my_arr[$id] = $name;
	}
        return $my_arr;
...

On a side note, I was going to mention using a fetch_all function that converts the result into an array, but unfortunately unlike PostGreSQL which has the pg_fetch_all function, MySQL does not have this function in PHP. :(

Fantastic. Figured it was something simple....and such a quick response!

Thanks!
Jeff

Member Avatar for Rkeast

Fantastic. Figured it was something simple....and such a quick response!

Thanks!
Jeff

:) No problem... It's Friday, work is slow, and I don't have any personal projects to work on :P...

Also, Welcome to DaniWeb!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.