Here's an example using JSON as the data exchange format. You could use XML, JSON, HTML or even pass javascript to be evaluated.
PHP:
$searchParam = $_GET['SEARCH_PARAM'];
//Get the matching results for the secondselect from your database
$results = $DB->query('Select ID, NAME, GROUP from mytable where parent = ?', $searchParam);
//If you're using a PHP 5.2 or a newer version you have the json_encode function
print json_encode($results);
HTML:
<select id="firstselect" onchange="myfunc();">
<option value="">Select one...</option>
<option value="1">One option</option>
<option value="2">Second choice</option>
</select>
<select id="secondselect"></select>
Javascript:
function myfunc() {
var value = $("#firstselect").val();
$.get("myjsonprovider.php",
{SEARCH_PARAM: value },
dataType: "JSON",
function(data) {
var options = '<option value="">Select one...</option>';
var optgroup = data[0].GROUP;
options += '<optgroup label="' + data[i].GROUP + '">';
for(var i = 0; i < data.length; i++) {
if(optgroup != data[i].GROUP) {
options += '</optgroup><optgroup label="'+data[i].GROUP+'">';
}
options += '<option value="' + records[i].ID +'">'+data[i].NAME+'</option>';
}
options += '</optgroup>';
$("#secondselect").html(options);
}
);
}