$query = "SELECT *, ((ACOS(SIN($lat * PI() / 180) * SIN(lat * PI() / 180) + COS($lat * PI() / 180) * COS(lat * PI() / 180) * COS(($lon - lon) * PI() / 180)) * 180 / PI()) * 60 * 1.1515) AS distance
FROM average_temp
HAVING distance<=25
ORDER BY distance ASC limit 1";
I can run the above query without any problems in phpmyadmin but it fails about 20% of the time if I run it through my php file.
This is the code that deals with the query results:
if (!$query){
die ("Query failed: " . mysql_error());
}
$result = mysqli_query($db, $query);
$num_results = mysqli_num_rows($result);
$row = mysqli_fetch_assoc($result);
$var = $row['id'];
80% of the time it works great and the other 20 it hangs for 30sec and throws this error:
Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given in C:\wamp\w
What I'm doing is taking latitude and longitude values from another table and referencing them with this table. The formula works like a charm on finding locations within a given distance. I have it set at 25 miles and only want the closest match but you could change it to give you the nearest # of locations. I found the query here.
Any ideas what I could be doing wrong?