Using a DB, I'd do it this way (tables used are from my SQL tutorial). Select a house name and the pupils menu lists pupils from that house.
<?php
const HOST = 'localhost';
const USERNAME = '????';
const PASSWORD = '????';
const DATABASE = 'jointute'; // default db
$db = pdoConnect();
//==============================================================================
// HANDLE AJAX CALLS
//
if (isset($_GET['ajax'])) {
if ($_GET['ajax']=='pupilopts') {
exit( json_encode(pupilOptions($db, $_GET['hid'])));
}
exit('INVALID REQUEST');
}
//==============================================================================
function houseOptions($db)
{
$opts = "<option value=''>- select house -</option>\n";
$res = $db->query("SELECT houseID
, house_name
FROM house
ORDER BY house_name
");
foreach ($res as $r) {
$opts .= "<option value='{$r['houseID']}'>{$r['house_name']}</option>\n";
}
return $opts;
}
function pupilOptions($db, $hid)
{
$opts = [];
$res = $db->prepare("SELECT pupilID
, CONCAT(lname, ', ', fname) as name
FROM pupil
WHERE houseID = ?
ORDER BY lname, fname
");
$res->execute([$hid]);
$pups = $res->fetchAll();
$opts = array_column($pups, 'name', 'pupilID');
sort($opts);
return $opts;
}
function pdoConnect($dbname=DATABASE)
{
$db = new PDO("mysql:host=".HOST.";dbname=$dbname;charset=utf8",USERNAME,PASSWORD);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
return $db;
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<title>Example</title>
<meta charset='utf-8'>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type='text/javascript'>
$().ready( function() {
$("#houses").change( function() {
var hid = $(this).val()
$.get(
"", // specify processing file on server (in this case it's same file)
{"ajax":"pupilopts", "hid":hid}, // data to send in request
function(resp) { // handle the response
$("#pupils").html("<option value=''> - select pupil -</option");
$.each(resp, function(k, v) {
$("#pupils").append($("<option>", {"val":k, "text":v}))
})
},
"JSON" // response type
)
})
})
</script>
<style type='text/css'>
body {
font-family: calibri, sans-serif;
font-size: 12pt;
}
div {
margin: 16px;
padding: 8px;
border: 1px solid gray;
}
label {
display: inline-block;
background-color: black;
color: white;
width: 120px;
padding: 8px;
margin: 1px 8px;
}
</style>
</head>
<body>
<div>
<label>House</label>
<select id="houses" >
<?= houseOptions($db) ?>
</select>
</div>
<div>
<label>Pupil</label>
<select id="pupils" >
<!-- pupil options -->
</select>
</div>
</body>
</html>