0

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.

4
  • Looks like you are just looping six times and printing the same thing six times for every city within 100 miles. Commented Jun 25, 2014 at 23:26
  • Sidenote: change if ($miles < "100") {...} to if (intval($miles) < 100) {...} Commented Jun 25, 2014 at 23:27
  • selecting everything by order rand() and calculating in php will be slow. if possible, calculate the distance on the db. see stackoverflow.com/questions/1006654/… Commented Jun 25, 2014 at 23:29
  • FuzzyTree, thanks for the link. My db will max out around 300-400 locations, so I think rand() should be ok, no? So far, it's plenty fast enough. Commented Jun 26, 2014 at 1:14

1 Answer 1

2

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...

Sign up to request clarification or add additional context in comments.

1 Comment

I see what you did there. Seems so simple now that I see it. Works like a charm! Only correction is that line 2 is missing some containers: while (($row = mysql_fetch_array($result)) && ($count < 6)) Thanks.

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.