<?php
/* SQL
CREATE TABLE `city` (
`id` tinyint(4) NOT NULL AUTO_INCREMENT,
`city` varchar(50) DEFAULT NULL,
`countryid` tinyint(4) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM;
INSERT INTO `city` VALUES(1, 'Los Angeles', 1);
INSERT INTO `city` VALUES(2, 'New York', 1);
INSERT INTO `city` VALUES(3, 'Toronto', 2);
INSERT INTO `city` VALUES(4, 'Vancouver', 2);
CREATE TABLE `country` (
`id` tinyint(4) NOT NULL AUTO_INCREMENT,
`country` varchar(20) NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
) ENGINE=MyISAM;
INSERT INTO `country` VALUES(1, 'USA');
INSERT INTO `country` VALUES(2, 'Canada');
*/
error_reporting(-1);
try {
$dbh = new PDO(
'mysql:dbname=test;host=localhost',
'root',
'root'
);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
function getCountries($db) {
$list = '';
$sql = 'SELECT id, country FROM country';
$stmt = $db->query($sql);
while( $row = $stmt->fetch(PDO::FETCH_ASSOC) ) {
$list[] = $row;
}
return $list;
}
function getCitiesFromID($id, $db) {
$list = '';
$sql = 'SELECT id, city FROM city WHERE countryid = ?';
$stmt = $db->prepare($sql);
$stmt->bindParam(1, $id, PDO::PARAM_INT);
$stmt->execute();
while( $row = $stmt->fetch(PDO::FETCH_ASSOC) ) {
$list[] = $row;
}
return $list;
}
if( isset($_GET['country']) ) {
echo json_encode( getCitiesFromID( $_GET['country'], $dbh ) );
die();
}
?>
<html>
<body>
<form id="testForm">
<label>Country</label>
<select name="country">
<option></option>
<?php
foreach( getCountries($dbh) as $row ) {
echo '<option value="' . $row['id'] .'">' . $row['country'] .'</option>';
}
?>
</select>
<label>City</label>
<select name="city"></select>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
$('#testForm select[name="country"]').on(
'change keyup',
function() {
var $citySelect = $('#testForm select[name="city"]');
$citySelect.empty();
if( parseInt(this.value) ) { // so we don't parse the empty option...
$.ajax({
url: 'test.php?country=' + this.value,
dataType: 'json',
success: function(data) {
$.each(data, function(k,v) {
$citySelect.append('<option value="' + data[k].id + '">' + data[k].city + '</option>');
});
}
});
}
}
);
</script>
</body>
</html>
Bookmarks