Jump to content


Photo

MySQL Data into Assoc Array


  • Please log in to reply
4 replies to this topic

#1 Bagwaa

Bagwaa
  • New Members
  • Pip
  • Newbie
  • 2 posts
  • LocationUK

Posted 08 August 2006 - 08:03 PM

Howdi,

Its been a while since I touched PHP and im having a problem, I have a really basic login script where the username and password are saved in the script, basically they are stored in an assoc array as follows :-

$authorized_users = array (
"bill" => "bill",
"guest" => "guest"
);

I have now created a table in a MySQL DB and I can connect to it and pull the information from it, however I cannot get the info into the array .. I was thinking of something like this :-

$authorized_users = array (
while ($row = mysql_fetch_row($result)) {
"$row[0]" => "$row[1]",
"guest" => "guest"
}
);

But obviously the syntax is all wrong, anyway .. hope im making SOME sense ... :-)

Thanks

Richard
Best Wishes, [br] [br]Richard Bagshaw [br]richard@bagshaw.co.uk

#2 corbin

corbin
  • Staff Alumni
  • Advanced Member
  • 8,129 posts

Posted 08 August 2006 - 08:07 PM

$authorized_users = array ();
while ($row = mysql_fetch_row($result)) {
  authorized_users[] = $row['user'];
}

Should work... I dont use arrays very often so I'm not sure...
Why doesn't anyone ever say hi, hey, or whad up world?

#3 Orio

Orio
  • Staff Alumni
  • Advanced Member
  • 2,491 posts

Posted 08 August 2006 - 08:08 PM

Try:
<?php
//let's say $result holds the resource mysql_query() gave
$authorized_users=array();
while($row=mysql_fetch_array($result)){
$authorized_users[$row['field1']]=$row['field2'];
}
?>

Is this what you want? (just replace "field1" and "field2" with what you want).

Orio.
Think you're smarty?

(Gone until 20 to November)

#4 Bagwaa

Bagwaa
  • New Members
  • Pip
  • Newbie
  • 2 posts
  • LocationUK

Posted 08 August 2006 - 08:13 PM

thanks for the replies guys ... and orio! many MANY thanks! it worked :-)

Best Wishes, [br] [br]Richard Bagshaw [br]richard@bagshaw.co.uk

#5 ToonMariner

ToonMariner
  • Members
  • PipPipPip
  • Advanced Member
  • 3,342 posts
  • LocationNewcastle upon Tyne, UK

Posted 08 August 2006 - 08:19 PM

If you want all the data from your query stored into an associative array (keeping the field names) try this...

<?php
$qry = "SELECT * FROM `yourtable`";
$qry = mysql_query($qry);

$arr = array();
while ($row = mysql_fetch_assoc($qry))
{
 foreach ($row as $key => $val)
 {
  $arr[$key][] = $value;
 }
}
?>

I think that is pretty elegant........
follow me on twitter @PHPsycho




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users