Jump to content

MySQL Data into Assoc Array


Bagwaa

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

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.