Log in

View Full Version : How to implement a zipcode lookup field



kuau
05-01-2010, 04:07 PM
I have a table of 43k zipcodes and I want to let users who are entering client addresses into a form enter the zipcode and have the city & state automatically fill in.

I tried this code but nothing shows up in the City State field...


<?php include_once('db-connectdb.php'); $sql = "SELECT citystate FROM zipcode WHERE zip = '".$_POST['zip']."'";
$result = mysql_query($sql,$connection) or die("Couldn't execute $sql query. <br> mysql error: ".mysql_error());
$row = mysql_fetch_row($result); $citystate = $row['citystate']; ?>
<p><label>City, State:</label><input type="text" name="citystate" size="40" value="<?php echo $citystate;?>"> Zip: <input type="text" name="zip" size="15"></p>

If they have already typed in a city, I'm not sure if it should replace what they typed either. Can anyone see what I am doing wrong? Thanks!

katierosy
05-04-2010, 06:59 AM
Please see if writing like this as below works.
<?php
include_once('db-connectdb.php');
$sql = "SELECT citystate FROM zipcode WHERE zip = '".$_POST['zip']."'";
$result = mysql_query($sql,$connection) or die("Couldn't execute $sql query. <br> mysql error: ".mysql_error());
$row = mysql_fetch_array($result,MYSQL_ASSOC);
$citystate = $row['citystate'];
?>
<p>
<label>City, State:</label>
<input type="text" name="citystate" size="40" value="<?php echo $citystate;?>">
Zip: <input type="text" name="zip" size="15">
</p>

kuau
05-06-2010, 02:47 AM
Dear Katierosy: I tried that code but nothing showed up in the citystate field when I entered the zip code. Thanks for trying. I'm surprised this isn't a very common script available everywhere, but no one seems to know how to make it work. I'd be happy to share the table of 43,377 zip codes if you can help me get it to work. :)

bluewalrus
05-06-2010, 03:00 AM
Are you submitting the form when you enter the zip, if not this will need to use javascript in some sort.