Jump to content

[SOLVED] PHP/MySQL Dependent Dropdowns


skyer2000

Recommended Posts

I've been looking everywhere on how to do this but have come up with no good results. What I have is a table with id, state, school.

 

I want to be able to have the user select a state, then the school dropdown will populate itself next to it, very similar to this http://examples.codecharge.com/CCSExamplePack2/DependentListBox/DependentListBox.php (except when the user clicks on school, it won't do anything because there is more to the form than just that)

Link to comment
https://forums.phpfreaks.com/topic/42766-solved-phpmysql-dependent-dropdowns/
Share on other sites

<?php

/**
* your first dropdown in your main page
*/


$sql = "SELECT DISTINCT state FROM schools ORDER BY state";
$res = mysql_query($sql) or die (mysql_error().'<p>$sql</p>');

echo "<select name='state' onchange='stateChanged(this.value)'>";
echo "<option value=''> - select state -</option>";

while ($row = mysql_fetch_row($res)) {
    echo "<option value='{$row[0]}'> {$row[0]}</option>";
}
echo '</select>';
?>

 

Then the script called by xmlhttp message is passed the "state" value in the query string

 

<?php
    $state = $_GET['state'];
    $sql = "SELECT id, school FROM schools 
            WHERE state = '$state' 
            ORDER BY school";
            
    $res = mysql_query($sql) or die (mysql_error().'<p>$sql</p>');
    echo "<select name='school' >";
    echo "<option value=''> - select school -</option>";

    while (list($id, $sch) = mysql_fetch_row($res)) {
        echo "<option value='$id'> $sch</option>";
    }
    echo '</select>';
        
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.