Sorry to double post, but got bored and decided to write this script anyway, which does what I described above:
Relies on two files, the main file and the lookup.php file that gets the cities via an AJAX request (relies on jQuery for this to work):
Main php file:
PHP Code:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.4.min.js"></script>
<script type="text/javascript">
$(document).ready( function () {
// Attach event handler to the countryselect element
$('#countryselect').change( function() {
if($(this).val() == '') {
$('#cityselect').html('<option value="">Please select a country first....</option>');
} else {
// Show the user that the script is actually doing something
// This won't ever really be seen when working on a local machine
$('#cityselect').html('<option value="">Loading cities...</option>');
// Send off AJAX request with the code the user specified
$.ajax({
url : 'lookup.php',
data : 'code=' + $(this).val(),
success : function(data) {
// Populate the city dropdown with the cities for the country
$('#cityselect').html(data);
},
type : 'get'
});
}
});
});
</script>
</head>
<body>
<?php
mysql_connect("localhost","root","") or die("Failed connect to the database");
mysql_select_db("countries") or die("Failed to select the database");
?>
<table><tr>
<td>Select Country:</td> <td><select name='statecountrycode' id='countryselect'> <option value=''></option>
<?php
$res1 = mysql_query("SELECT * FROM country");
if($res1) {
while($row=mysql_fetch_array($res1)) {
echo "<option value='" . $row['Code'] . "'>". $row['Name'] . "</option>";
}
}
?>
</select></td>
</td></tr>
<tr><td>Select City:</td><td><select name='statecountryode' id='cityselect'> <option value='0'>Please select a country first...</option>
</select></td></tr>
</table>
</body>
</html>
lookup.php:
PHP Code:
<?php
if(isset($_GET['code'])) {
// Connect / select to the database
mysql_connect("localhost","root","") or die("Failed to connect to the server");
mysql_select_db("countries") or die("Failed to select the database");
// Escape input for query
$code = mysql_real_escape_string($_GET['code']);
// Select all cities for the given code
$SELECT_CITIES = "SELECT * FROM city WHERE CountryCode = '" . $code ."'";
$CITIES = mysql_query($SELECT_CITIES);
// Loop through the cities and output HTML for JavaScript to use
while($city = mysql_fetch_array($CITIES)) {
echo '<option value="' . $city['ID'] . '">' . $city['Name'] . '</option>';
}
}
?>
This will work with the tables created via the world.sql file that hemi519 provided.
Bookmarks