Dependent Drop Down in PHP Using MYSQL data

Discussion in 'PHP' started by mike_01, May 7, 2008.

  1. #1
    Hia,

    I got stuck with populating the child drop down menu when the parent drop down is selected in the php file with data being fetched from the MYSQL database. I am entering the information in the database with different areas being entered into different cities.

    One drop down is for the City and the other one is for the areas under the given city is selected but I am not able to use the function to call the data in the child drop down of the search form.

    I would really appreciate if someone can guide me to the right way to do this.

    Thanks,
    Mike...
     
    mike_01, May 7, 2008 IP
  2. bokiatenxi

    bokiatenxi Peon

    Messages:
    27
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #2
    this is actually easy if you have some background on javascript...

    assuming your page is named mypage.php...

    first, add an onChange trigger on the parent dropdown, something like this ;

    <select name='city' onChange='javascript: getChildDropdown(this);'>

    also note that the value on your <option> tag should be the key of the city ;

    <option value='1'>City Name</option> // 1 is the primary key for the city

    then add a javascript function on your page (on the head part) like this ;

    <script>
    function getChildDropdown(parentval) {
    parentval = parentval.value;
    window.location.href('mypage.php?parent='+parentval);
    }
    </script>

    then add a line like this on top of your php page ;

    if(isset($_GET['parent']) && $_GET['parent'] != '') {
    // query for the child data using the $_GET['parent'] as your key
    // populate the dropdown the same way you populated the parent dropdown
    }

    and thats it..

    Hope it helps...

    And by the way, it would be better if you know ajax, that way the page wont have to load everytime you change the parent dropdown...
     
    bokiatenxi, May 8, 2008 IP