Re: Using two colomns of mysql data as key/value pairs in arrays

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Devon --

...and then Devon said...
% 
...
%   SELECT id, name FROM a_table;
% 
% I just cannot figure out how to get that data from the resource handle 
% into an associative array with the 'id' colomn making up the keys and 
% the 'name' colomn making up the values.

You won't get that directly; you'll have to build your final array
from the results.

You can read your info out of the DB as an indexed or associative array
(via mysql_fetch_array) or just as values (mysql_fetch_row), but you'll
only get one result at a time.  You need to loop through the results with
something like

  $result = mysql_query("select id,name from a_table") ;
  $everyone = () ;
  while ( $row = mysql_fetch_array($result) )
    { $everyone[$row['id']] = $row['name'] ; }

or so to fill up $everyone so that you can then look up by $everyone[$id].

Note that I don't recommend this as the best approach, and I don't think
that anyone else does, either.  Usually you want to avoid sucking an
entire database into your script's memory; the database (and its coders)
almost always handles data better than we mere mortals.  A much better
approach is to make your select call per specific ID and get out only the
name(s) that you need, and then go back later and make a different call.
The only time I can see sense in scanning the whole table is when you
want to dump the entire list of people or some such, and then rather than
doing it in two steps of loading your $everyone and then spitting out I'd
probably do something like

  $sql = "select id,name from a_table order by department" ;
  $result = mysql_query($sql) ;
  while ( $row = mysql_fetch_array($result) )
    { print "ID: {$row['id']}\tName: {$row['name']}<br>\n" ; }

to just run through the data.  I'm sure others here know of even better
ways to print a roster :-)


% 
% Any help would be wonderful! :)


HTH & HAND

:-D
-- 
David T-G                      * There is too much animal courage in 
(play) davidtg@justpickone.org * society and not sufficient moral courage.
(work) davidtgwork@justpickone.org  -- Mary Baker Eddy, "Science and Health"
http://justpickone.org/davidtg/      Shpx gur Pbzzhavpngvbaf Qrprapl Npg!

Attachment: pgp00061.pgp
Description: PGP signature


[Index of Archives]     [PHP Home]     [PHP Users]     [Postgresql Discussion]     [Kernel Newbies]     [Postgresql]     [Yosemite News]

  Powered by Linux