0

I am using a db query that takes in a state and city then spits out 10 fields. Currently I can only see those fields by using print_r. I tried a suggestion on the php manual site a for loop to print the fields however I can't get it to work properly. Here is the code:

    if (!$result) {
        echo 'Could not run query: ' . mysql_error();
        exit;
    }
    if (mysql_num_rows($result) > 0) {
        while ($row = mysql_fetch_assoc($result)) {
            print_r($row)."</p>";
            $arrayLength = count($row);
            for ($i = 0; $i < $arrayLength; $i++){
                echo "arrayName at[" . $i . "] is: [" .$row[$i] . "]<br>\n";
            }
                
                
        }

    }

And this is the result:

Array ( [id] => 1299 [zip_code] => 04011 [city] => Brunswick [county] => Cumberland [state_name] => Maine [state_prefix] => ME [area_code] => 207 [time_zone] => Eastern [lat] => 43.9056 [lon] => -69.9646 ) ....
arrayName at[0] is: []
arrayName at[1] is: []
arrayName at[2] is: []
arrayName at[3] is: []
arrayName at[4] is: []
arrayName at[5] is: []
arrayName at[6] is: []
arrayName at[7] is: []
arrayName at[8] is: []
arrayName at[9] is: []

Any ideas why I am not able to properly print the fields and their values? Also my code fails if the query returns more than one row as the current code doesn't really accommodate it.

I put $i in the body of the for loop to see if it was working properly. Ideally I would have the field name where $i is and the value to the right of it after the colon.

4 Answers 4

3

you are fetching with mysql_fetch_assoc so change loop into

foreach($row as $key => $value){
echo "Array key : $key = $value <br/>";
}
Sign up to request clarification or add additional context in comments.

Comments

3

Your array keys are 'id', 'zip_code' etc. There's nothing in the 0, 1 etc. indexes of the array.

foreach ($row as $key => $value) {
    echo "arrayName at[" . $key . "] is: [" . $value . "]<br>\n";
    // which is the same as:
    echo "arrayName at[" . $key . "] is: [" . $row[$key] . "]<br>\n";
}

Comments

0

Yes, because that returns an associative array That means that you have to access the elements like so: $row["id"] for instance

What you want is this

foreach($row as $key => $value)
echo "arrayName at[" . $key . "] is: [" .$value . "]<br>\n";

Comments

0

use mysql_fetch_array() instead of mysql_fetch_assoc()

the mysql_fetch_assoc() will return an associative array and only accessable via $row['name']. With mysql_fetch_array() you can fetch an associative array, a numeric array, or both.

take a look here: http://www.php.net/manual/en/function.mysql-fetch-array.php

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.