Bill
Bill

Reputation: 5688

output an associative array, from SQL Select with PHP

I think my mind is just drawing a blank, but basically, I want to create an associative array from various sql results

The array needs to look like:

$people = array(
     "+1123456789" => "Phil"
);

Here is my SQL Statement

$sql = " SELECT phonenumber6, firstName FROM members WHERE departmentID = 4 AND phonenumber6 <> '+1';";

Thanks!

Edit: Also, there can be multiple rows that were selected by the sql statement

$sql = " SELECT phonenumber6, firstName FROM members WHERE departmentID = 4 AND phonenumber6 <> '+1';";

                $result = mysql_query($sql);

                while($row=mysql_fetch_assoc($result)) {
                  echo $people[$row['phonenumber6']] = $row['firstName'];
                }

Upvotes: 0

Views: 2479

Answers (2)

S. Albano
S. Albano

Reputation: 707

This will give you an associated array from a mysql result set:

$assoc = mysql_fetch_assoc ($res);

Upvotes: 0

dynamic
dynamic

Reputation: 48141

while($row=mysql_fetch_assoc($query)) {
  $people[$row['phonenumber6']] = $row['firstName'];
}

Addendum

Dunno what you want to echo. Anyway the right syntax is:

while($row=mysql_fetch_assoc($query)) {
  $people[$row['phonenumber6']] = $row['firstName'];
  echo $row['phonenumber6']. '=> '.$row['firstName']."<br />\n";
}

Upvotes: 3

Related Questions