Jump to content

Archived

This topic is now archived and is closed to further replies.

Bagwaa

MySQL Data into Assoc Array

Recommended Posts

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

Share this post


Link to post
Share on other sites
$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...

Share this post


Link to post
Share on other sites
Try:
[code]<?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'];
}
?>[/code]

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

Orio.

Share this post


Link to post
Share on other sites
thanks for the replies guys ... and orio! many MANY thanks! it worked :-)

Share this post


Link to post
Share on other sites
If you want all the data from your query stored into an associative array (keeping the field names) try this...

[code]
<?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;
}
}
?>
[/code]

I think that is pretty elegant........

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.