0

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

2
Contributors
3
Replies
4
Views
7 Years
Discussion Span
Last Post by Rkeast
0

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. :(

Edited by Rkeast: n/a

0

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

Thanks!
Jeff

0

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!

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.