PHP Fetch Array into Custom Array

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
ChrisJohnston
Forum Newbie
Posts: 2
Joined: Thu May 27, 2010 7:37 pm

PHP Fetch Array into Custom Array

Post 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.
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: PHP Fetch Array into Custom Array

Post 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>';
ChrisJohnston
Forum Newbie
Posts: 2
Joined: Thu May 27, 2010 7:37 pm

Re: PHP Fetch Array into Custom Array

Post 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!
Post Reply