My sql database has a table called address. The names of two of its fields are latitude and longitude. When I iterate through the results using the while loop and a foreach loop, I get all of the values of each field associated with its corresponding column. However, I do not see how to get each value separately because each value is associated with the same key (either a number if I use mysqli_fetch_array or a string if I use mysqli_fetch_assoc), i.e. - latitude or longitude.
My question is: How do I get to the separate values so that I can work with them?
Below is a snippet of the relevant code:
<?php
// use returned data // onclick send to google // have results sent to maps page
while($coords = mysqli_fetch_array($result)) {
foreach ($coords as $key => $val) {
echo "<pre>$key = $val <br /></pre>";
}
?>
Below are snapshots of my results:
array
assoc
Thank you for any time you might have to look at this.
The entire set of results includes two sets of columns–one with the column names and one with the column indexes.
$row = mysqli_fetch_array($result, MYSQLI_NUM); will return just the results with column indexes (most of the time, this is not needed).
$row = mysqli_fetch_array($result, MYSQLI_ASSOC); will return just the results with the column names (this is probably what you’re looking for if you want the results all at once).
You don’t even need the $lattitude and $logitude fields as you can reference $coords[‘latitude’] and $coords[‘longitude’] directly from the echo statement.
If you are going to use the extra fields then you should be sanitizing the values as a part of the assignment. Both fields should be numbers so anything that isn’t valid in a number should be stripped out. Of course if the database fields are one of the numeric formats then this is unnecessary.
Ya, ya… Ha ha. Got me again. He was echoing variables, so I echoed variables. He should only query fields he needs. How he formats the output I guess depends on what it’s used for. Does he need to build a specific array to use with mapquest, just echo results, compare one to another etc.