Page 1 of 1

[SOLVED] Using mysql_fetch_array()

Posted: Sat Sep 11, 2004 12:20 pm
by charp
Let's say I have a table called states with only two colums. Column 1 (abbr) is the two letter abbreviation for the state and column 2 (full) is the full name for the state.

Now I grab all the table data like this:

Code: Select all

<?php
$results=mysql_query("SELECT * FROM states");

$myArray=mysql_fetch_array($states);
?>
Now my questions is how do I access the data within this array called $myArray? I assumed that the abbr column was the key and the full column was the value. So, I tried $myArray[CA] thinking it would return California, but got zip.

I know that I can use this array in a loop to access all the data by rows using $myArray[abbr] and $myArray[full]. It seems that using mysql_fetch_array doesn't set the key=>value pairing as I thought it would.

Obviously, I'm missing something here, but I just don't know enough to spot it on my own. The two books I'm using to teach myself PHP have failed me this instance.

Anyone? Thanks in advance!

Posted: Sat Sep 11, 2004 12:25 pm
by McGruff
You should refer to string array keys like this:

Code: Select all

$array['foo']; // good
$array[foo]    // bad
It's sometimes useful to print out an array to see exactly what's in it:

Code: Select all

echo '<pre>';
print_r($myArray);
echo '</pre>';

Posted: Sat Sep 11, 2004 3:25 pm
by charp
Fixed the single qoute thing, but that wasn't my problem. Perhaps I wasn't clear in the first place. Let's see if this clarifies my question:

This code:

Code: Select all

<?php
while ($test=mysql_fetch_assoc($states)) {
echo 'abbr: '.$test['abbr'].' full: '.$test['full'].'<br>';
}
?>
Produced this result:

Code: Select all

abbr: CA full: California
abbr: AZ full: Arizona
abbr: MN full: Minnesota
What I'd like to be able to do is this:

Code: Select all

<?php echo $states['CA']; ?>
and produce this:

Code: Select all

California
But of course, I'm doing something wrong and I'm not getting any such results.

Posted: Sat Sep 11, 2004 3:27 pm
by feyd

Code: Select all

$states = array();
while($row = mysql_fetch_assoc($results)) $states[$row['abbr']] = $row['full'];

Posted: Sat Sep 11, 2004 5:41 pm
by charp
feyd, you've helped me before and I have to say you continue to be amazing. As I look at your solution, it's so simple. I hate to say how long I spent trying to come up with the solution on my own. Let's just say you saved me a lot of time and headaches.

Thank you so very much!