Webmaster Web Tools
Easy to Use Web Tools
Signups, Calendars, Slideshows,
Podcasts for iTunes, and more.
www.webpasties.com

Back to WebPasties
Back to Step #5

Step #6 - Querying the ZIP Code Database

We will retrieve the matching city and state from our zipcodes table by performing a simple query. Using the code below, modify lines 9-11 to reflect your database settings and then save the file as getCityState.php

Once you have changed the code to reflect your database settings, a good way to test this file is to use your Web browser and launch its URL complete with a query string containing a ZIP code. An example of what the URL would look like is the following:
http://localhost/step6/getCityState.php?param=17534

Did the above URL produce a city,state pair as output? If so you are good to go.

Try out the ZIP code functionality with the HTML file you created containing the XMLHttpRequest code.

Line 1 :
Line 2 :
Line 3 :
Line 4 :
Line 5 :
Line 6 :
Line 7 :
Line 8 :
Line 9 :
Line 10:
Line 11:
Line 12:
Line 13:
Line 14:
Line 15:
Line 16:
Line 17:
Line 18:
Line 19:
Line 20:
Line 21:
Line 22:
Line 23:
Line 24:
Line 25:
Line 26:
Line 27:
Line 28:
Line 29:
Line 30:
Line 31:
Line 32:
Line 33:
Line 34:
Line 35:
<?php
/**
* Connects to the database.
* Return false if connection failed.
* Be sure to change the $database_name. $database_username , and
* $database_password values  to reflect your database settings.
*/
function db_connect() {
  
$database_name =
'mysql'
; // Set this to your Database Name
  
$database_username =
'root'
; // Set this to your MySQL username
  
$database_password =
''
; // Set this to your MySQL password
  
$result = mysql_pconnect('localhost',$database_username, $database_password);
  if (!
$result) return false;
  if (!
mysql_select_db($database_name)) return false;
  return
$result;
}
$conn = db_connect(); // Connect to database
if ($conn) {
  
$zipcode = $_GET['param']; // The parameter passed to us
  
$query = "select * from zipcodes where zipcode = '$zipcode'";
  
$result = mysql_query($query,$conn);
  
$count = mysql_num_rows($result);
  if (
$count > 0) {
    
$city = mysql_result($result,0,'city');
    
$state = mysql_result($result,0,'state');
  }
}
if (isset(
$city) && isset($state)) {
  
$return_value = $city . "," . $state;
}
else {  
  
$return_value = "invalid".",".$_GET['param']; // Include Zip for debugging purposes
}
echo
$return_value; // This will become the response value for the XMLHttpRequest object
?>

Step #6 Source Code



To Step #7 - Room for Improvement