Jump to content

php zipcode search


jpratt

Recommended Posts

I am doing a zipcode search so it is looping through and first finding the records that match the user zipcode, then searching the match of the first four of the zip, then the first 3 and so on. Here is how i am doing it:

 

$zippos = 5;
while ($zippos > 0) {	
$userzip = substr($zipin, 0 ,$zippos);

$sqlwsearch = "SELECT * FROM whitepage WHERE SUBSTRING(Zip, 1, '$zippos') = '$userzip'";

$resultw = mysql_query($sqlwsearch);
$numrows = mysql_num_rows($resultw);

        //display results here
$zippos--;
}

 

My question is how do I get it not to repeat results that match each loop through? if I have a zip in the database of 12345 and i search 12347, I dont want it repeated 4 times in my results. Any ideas?

Link to comment
https://forums.phpfreaks.com/topic/77170-php-zipcode-search/
Share on other sites

You can set a flag variable when you find a match and only search when you haven't matched:

<?php
$matched = false;
for ($zippos = 5; $zippos > 0 && !$matched; $zippos--) {
$userzip = substr($zipin, 0 ,$zippos);

$sqlwsearch = "SELECT * FROM whitepage WHERE SUBSTRING(Zip, 1, '$zippos') = '$userzip'";

$resultw = mysql_query($sqlwsearch);
$numrows = mysql_num_rows($resultw);
        if ( matched_condition ) $matched = true;
}?>

replace "if ( matched_condition )" with your matching criteria.

 

Ken

Link to comment
https://forums.phpfreaks.com/topic/77170-php-zipcode-search/#findComment-390758
Share on other sites

so now this is what I have:

$matched = false;

for ($zippos = 5; $zippos > 0 && !$matched; $zippos--) {	
$userzip = substr($zipin, 0 ,$zippos);

$sqlwsearch = "SELECT * FROM whitepage WHERE SUBSTRING(Zip, 1, '$zippos') = '$userzip'";

$resultw = mysql_query($sqlwsearch);

while ($row = mysql_fetch_array($resultw)) {
	if ((substr($row['Zip'], 0, $zippos)) == $userzip) {
		$matched = true;
		echo "<p><table id='white'><tr><td id='company'>" . $row['CompanyName'] . "</td></tr>";
		echo "<tr><td>" . $row['Address'] . "</td></tr>";
		echo "<tr><td>" . $row['City'] . ", " . $row['State'] . " " . $row['Zip'] . "</td></tr>";
		echo "<tr><td>http://www." . $row['WebLink']. "</td></tr></table></p>";
	}

}
}

 

it is now returning the results of the matches up to  the first 2 characters of the zip. so I have the zip codes of 80016, 84372, 84532, and 87824. If i search for 84125 it returns the two starting with 84. Any ideas why it is not returning the other two?

Link to comment
https://forums.phpfreaks.com/topic/77170-php-zipcode-search/#findComment-390780
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.