Page 1 of 1

PHP Fetch Array into Custom Array

Posted: Thu May 27, 2010 7:39 pm
by ChrisJohnston
Hi!

I was just wondering if anybody could help me figure out how to do this:

I want to select from my database "id" and "name", then I want to echo these out in a drop-down list. The way I have coded this is that I need to create an array like this:
array("1" => "Chris", 2" => "Johnston");

I'm wondering how I could go about it. I've tried mysqli_fetch_array() and only selecting the id and the name columns, but it only shows the name in my drop down without assigning the value of the id related to that name.

Also, I cannot use a counter as there are other variables involved in the WHERE clause.

I basically want to be able to do this:
array($myfetchedarray[id] => $myfetchedarray[name]);

Also, I cannot echo it out as the following:
<select value="$myfetchedarray[id]">$myfetchedarray[name]</select>
as this is an OOP script that requires an array.

Thank you in advance.

Re: PHP Fetch Array into Custom Array

Posted: Thu May 27, 2010 7:51 pm
by John Cartwright
I'm not exactly sure what your problem is, but I think this example should clarify the process a little better.

Code: Select all

function getNames() {
   $return = array();

   $sql = "
      SELECT id, name
      FROM users
   ";
   $result = mysql_query($sql) or die(mysql_error());

   while ($row = mysql_fetch_assoc($result)) {
      $return[$row['id']] = $row['name'];

      //or my preference would be to store the entire row
      //$return[$row['id'] = $row;
   }

   return $return;
}


//... later on in html land

$names = getNames();

echo '<select name="yourelementname">';
foreach ($names as $id => $name) {
   echo '<option value="'. $id .'">'. $name .'</option>';
}
echo '</select>';

Re: PHP Fetch Array into Custom Array

Posted: Fri May 28, 2010 1:13 am
by ChrisJohnston
Thank so you much! I love you I love you I love you!

I didn't realise it was that simple, I've been doing this stuff for years and have never come across the need to do such a thing nor have I been able to find anything on Google. Thanks again!