I’ve got a problem that’s probably pretty basic, but completely puzzling me.
I have a website that pulls nearby zip codes from a location (i.e. if I make my location Detroit, Michigan then I get the zip codes 48201, 48272, 48260, 48226, 48255, 48275, 48267, 48231, 48268, 48278, etc.) The amount it grabs is variable (Detroit gets 28, Baltimore, MD gets 15).
The website is grabbing nearby locations for deliveries of flowers (In this case, the location is funeral homes).
If there are no funeral homes in the current zip code (i.e. 48201) it should then check neighboring zip codes from $zipListArray (48272, etc) until 5 results are found.
I have tried two different bits of code…
$num_rows = mysql_num_rows($result); //This is from the previous query, where it checks the immediate zip code
$i = 0;
while ($num_rows < 5) {
$result = mysql_query('SELECT funeralh_name, address1, city, state_abbr, zipcode, phone FROM funeral_homes WHERE city != "" AND zipcode = "'.$zipListArray[$i].'" AND state_abbr = "'.$abbr.'"');
$num_rows = mysql_num_rows($result);
$i++;
}
This code would be an infinite loop on any smaller city or group of cities where there are not 5 neighboring funeral homes.
$inc = 0;
if ($num_rows == 0) {
foreach ($zipListArray as $zip) {
$result = mysql_query('SELECT funeralh_name, address1, city, state_abbr, zipcode, phone FROM funeral_homes WHERE zipcode = "'.$zip[$inc].'"');
$total = 0;
$num_rows = mysql_num_rows($result);
$total += $num_rows;
if ($total == 5){
break;
}
$inc++;
}
}
This one I couldn’t get to work at all.
You’d be better off doing a
WHERE ... INsearch for all of those possible zipcodes, e.g.This way you only run one query, you get all possible zips, and you can add LIMIT clauses to restrict the results to only 5 rows – or only fetch a max of 5 rows. Either way, you eliminate that for() loop so you don’t end up with the infinite loop in case there aren’t 5+ nearby flower places in the first place.