Reputation: 88
So this has been driving me nuts for several days. I've tried THIS and THAT but nothing is working. Here's the basic rundown:
I have a MySQL database with 200 or so locations. The user enters their zip code, and I want to give them 6 random locations within 100 miles of home. Everything works great, except I can't get it to limit the results to 6. It will give me ALL the results for <100. When I try the code below (adding the for ($x=0...)
bit), I get the same result, only each one repeats 6 times before listing the next one. Here's the pertinent code that returns all the locations. Any help would save me from throwing my computer out the window.
$sql = "SELECT * FROM locations ORDER BY RAND()";
$result = mysql_query($sql, $dbase2);
while ($row = mysql_fetch_array($result))
{
$city = $row['city'];
$id= $row['id'];
$miles = calculateDistance($lat, $lon, $point2_lat,$point2_lon);
if ($miles < "100")
{ for ($x=0; $x<6; $x++){
echo $city . " is about " . round($miles) . " miles away.<br />";
};
};
};
Like I said, for the sake of this post, I tried to pare it down to the important bits. Let me know if something vital is missing from my example.
Upvotes: 0
Views: 1880
Reputation: 46365
The following change should do it:
$count = 0;
while (($row = mysql_fetch_array($result)) && ($count < 6))
{
$city = $row['city'];
$id= $row['id'];
$miles = calculateDistance($lat, $lon, $point2_lat,$point2_lon);
if ($miles < 100.0) {
echo $city . " is about " . round($miles) . " miles away.<br />";
$count = $count + 1;
};
};
There are more elegant ways...
Upvotes: 2