I am working on a website that will show the nearest store locations to a specific location. I am using the haversine formula to determine the distance and everything is working except the XML cannot see the distance field that I have created.
switch($unit) {
case "km":
$distance = 6371; // KM
break;
case "mi":
$distance = 3959; // KM
break;
}
$query = "SELECT store_id, name, address, description, longitude, latitude,
(? * acos(cos(radians(?)) * cos( radians(latitude)) * cos(radians(longitude)
- radians(?)) + sin(radians(?)) * sin(radians(latitude))))
AS distanceFromLocation FROM stores";
$stmt = $mysqli->prepare($query);
$stmt->bind_param('iddd', $distance, $user_latitude, $user_longitude, $user_latitude);
$valid_statement = true;
try {
$stmt->execute();
$stmt->store_result();
} catch(Exception $e) {
$valid_statement = false;
error_log($e->getMessage());
}
if($valid_statement) {
$stmt->bind_result($store_id, $name, $address, $description, $longitude, $latitude, $distanceFromLocation);
while($stmt->fetch()) {
echo $distanceFromLocation;
$node = $dom->createElement("marker");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("storeid", $store_id);
$newnode->setAttribute("name", $name);
$newnode->setAttribute("address", $address);
$newnode->setAttribute("lat", $latitude);
$newnode->setAttribute("lng", $longitude);
$newnode->setAttribute("distance", $distanceFromLocation);
}
}
The distanceFromLocation variable is always empty when it gets in the the while loop. I have tested the SQL and it will return the correct distance values. Any ideas why I cannot access the distance field? Is it because it is a calculated field?
You need to incorporate the result from switch as the first parameter. I also changed $distance to $constant for clarity.