How to link a double drop down menu dynamically

Codes here !

Moderators: egami, macek, gesf

Post Reply
mattcuk
New php-forum User
New php-forum User
Posts: 1
Joined: Tue Sep 05, 2017 5:23 am

Wed Sep 06, 2017 10:13 am

Hi All

I have a mySQL database table called countries which contains 4 columns (id, country, city, url). I'm trying to create a php form with two drop downs, one asking for country then I want the second drop down to populate a list of cities based on the country selected in the first drop down. Then on submit, I want the page to direct to a url (stored in the db). So far I have two drop downs working which populate from the database but I don't know how to dynamically populate the cities drop down based on the country selection. I need to do this in wordpress using PHPCode Snippets so a one page solution is preferred via php.

Code: Select all

$conn=mysqli_connect($server, $username, $pass, $dbname);
if (!$conn) {
exit('Connect Error (' . mysqli_connect_errno() .' )' 
   . mysqli_connect_error());
}
echo"<div class=\"label\">Select Country:</div>";
echo"<select name=\"countries\">";
echo"<option value= \"\">---Select your country---</option>";
$querycountries = "SELECT * FROM countries GROUP BY country ORDER BY 
country";
    $conn = mysqli_query($conn, $querycountries);
    while ( $d=mysqli_fetch_assoc($conn)) {
      echo "<option value='{".$d['id']."}'>".$d['country']."</option>";
    }
echo"</select><br><br>";
$conn2=mysqli_connect($server, $username, $pass, $dbname);
if (!$conn2) {
exit('Connect Error (' . mysqli_connect_errno() .' )' 
       . mysqli_connect_error());
}
echo"<div class=\"label\">Select City:</div>";
echo"<select name=\"cities\">";
echo"<option value= \"\">---Select your city---</option>";
$querycities = "SELECT * FROM countries ORDER BY city";
    $conn2 = mysqli_query($conn2, $querycities);
    while ( $d=mysqli_fetch_assoc($conn2)) {
      echo "<option value='{".$d['id']."}'>".$d['city']."</option>";
    }
echo"</select>";
Thanks for any help

Matt

Post Reply