2

I have two dropdown lists, the first is populated from database and works fine, the second dropdown must be populated dynamically from what user has chosen from the first dropdown list. For example, my first dropdown contains many country's name, when user choose a country, the second dropdown will be populated by city's of that country which are in same database. Have anyone an example of this?

This is the first dropdown list

  <select size="1" name="listeOrg">
        <option value = "0" selected>---Choisir une région---</option>
    <?php
        $link3 = mysql_connect_db();

$query3 = "SELECT nom_region FROM region ";
$result3 = mysql_query($query3, $link3) or die();


while ($row = mysql_fetch_array($result3)) {
echo '<option value="'.$row['nom_region'].'">'.$row['nom_region'].'</option>';
}
 mysql_close($link3);  ?>                                                   
                    </select>  

And the second:

 <?php
        $link4 = mysql_connect_db();
$selectregion=$_POST['listeOrg'];
   $query4 = "SELECT organisme FROM region_organisme where nom_region='$selectregion' ";
  $result4 = mysql_query($query4, $link4) or die();


while ($row2 = mysql_fetch_array($result4)) {
 echo '<option value="'.$row2['nom_region'].'">'.$row2['nom_region'].'</option>';
}
  mysql_close($link4);  ?>  
  <option value="1" >autre

                </select> 
hamza-don
  • 455
  • 5
  • 26
  • You refer to $row2['nom_region'] while populating the second select, but you select 'organisme' field with your query. You should probably use $row2['organisme'] in your second loop?.. – Zoltán Tamási Mar 19 '14 at 20:49
  • I think you are better off using AJAX/jQuery here. Your code could also be open to SQL Injection. http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php http://stackoverflow.com/questions/6857287/how-to-make-a-cascading-drop-down-list-in-php-using-jquery – Maximus2012 Mar 19 '14 at 20:57
  • zoltan you're right, i changed it but no result i think i will try maximus suggestion, thanks ok Maximus i will try that – hamza-don Mar 20 '14 at 13:17

1 Answers1

3

I found finally a good solution with a proper code. This is the link to the tutorial if someone has been stacked on this case.

A good explained tutorial with demo

hamza-don
  • 455
  • 5
  • 26