Triple dependent drop down using MySQL and PHP

I am new to all of this and I’m totally lost.
:confused2

I have the following ‘Customer’ table in a MySQL database:

CustomerID
CustomerName
Address
City
StateProv
PostalCode
Country

There are numerous customers and I need three drop down
lists that allow the user to select a Country then based
on that country, the next drop down list will list the
states for that country. After a state is selected the
third drop down box will contain a list of the cities
for that state. There will be a button at the bottom of
the lists (Display List) this sends these choices to a
new page that displays only the customers for the country,
state and city chosen.

I have been trying to avoid using JavaScript, so I have
come up with the following code. The problem is I get the
list of countries, but the information is not passed to the
selectCountry variable, so nothing works.

Can anyone tell me what I’m missing?

:bawling:


<?php

include("db.php");
mysql_select_db($dbname);

if (isset($HTTP_POST_VARS['clear'])) {
unset($HTTP_POST_VARS['selectCity']);
unset($HTTP_POST_VARS['selectState']);
unset($HTTP_POST_VARS['selectCountry']);
}

if (!isset($HTTP_POST_VARS['selectCountry'])) {
$selectCountry = "";
}
if (!isset($HTTP_POST_VARS['selectState'])) {
$selectState = "";
}
if (!isset($HTTP_POST_VARS['selectCity'])) {
$selectCity = "";
}

$cityList = array();
$stateList = array();
$countryList = array();

$get_countries = mysql_query("SELECT DISTINCT (Country) FROM `Customer` ORDER BY Country ASC ");
if (!$get_countries) {
print "get_countries<br>";
print mysql_error() . "<br><br>";
}

if (isset($HTTP_POST_VARS['selectCountry']))
{
    $selectCountry = $HTTP_POST_VARS['selectCountry'];
    $get_states = mysql_query("SELECT DISTINCT (StateProv) FROM Customer WHERE Customer.Country = '$selectCountry' ORDER BY StateProv ASC");
    if (!$get_states) {
    print "get_state<br>";
    print mysql_error() . "<br><br>";
    }
}

if (isset($HTTP_POST_VARS['selectCity'])) {
    $selectState = $HTTP_POST_VARS['selectState'];
    $selectCity = $HTTP_POST_VARS['selectCity'];
    $get_cities = mysql_query("
    SELECT DISTINCT (City) FROM Customer WHERE Customer.StateProv = '$selectState' AND Customer.Country = '$selectCountry'");
    if (!$get_cities) {
    print "get_cities<br>";
    print mysql_error() . "<br><br>";
    }
}

if (@mysql_num_rows($get_countries)!=0) {
while ($item = mysql_fetch_array($get_countries)) {
if ($item["selectCountry"] == $selectCountry) {$sel = " selected";} else {$sel = "";}
array_push ($countryList,"<option value=\\"" . $item["selectCountry"] . "\\" " . $sel . ">" . $item["Country"] . "</option>");
    }
}
else {
array_push ($countryList,"<option>---------</option>");
}

if (@mysql_num_rows($get_states)!=0) {
while ($item = mysql_fetch_array($get_states)) {
if ($item["State"] == $selectState) {$sel = " selected";} else {$sel = "";}
array_push ($cityList,"<option value=\\"" . $item["selectState"] . "\\" " . $sel . ">" . $item["State"] . "</option>");
    }
}
else {
array_push ($cityList,"<option>---------</option>");
}

if (@mysql_num_rows($get_cities)!=0) {
while ($item = mysql_fetch_array($get_cities)) {
if ($item["City"] == $selectCity) {$sel = " selected";} else {$sel = "";}
array_push ($stateList,"<option value=\\"" . $item["selectCity"] . "\\" " . $sel . ">" . $item["City"] . "</option>");
    }
}
else {
array_push ($stateList,"<option>---------</option>");
}

?>

<html>
<head>
<title>Directory</title><meta name="Microsoft Border" content="b, default"
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

</head>

<body>
<table border="1" width="950" cellpadding="5">

  <tr>
  	<td width="150" valign="top" bgcolor="#33CCFF">
	<?
        include('mainMenu.inc');
    ?>
	</td>
    <td valign="top" >
		<?
	      include('chooseHeader.inc');
		?>
		<table width="800" cellpadding="5">
		<p align="left"><font size="3" face="Verdana, Arial, Helvetica, sans-serif">
		Select the name of the country, press 'SELECT'. A list of states will appear,
		Select the name of the state, press 'SELECT'. A list of cities will appear,
		Select the name of the city, press 'SELECT'.
		Use the 'DISPLAY LIST' button to see the cities listed the chosen state.</font><font size="3" face="Verdana, Arial, Helvetica, sans-serif">
		</font></p>
		
		<?php
		if (isset($_SERVER)) $PHP_SELF = $_SERVER['PHP_SELF'];
		?>
		
		<FORM ACTION="<?php print $PHP_SELF; ?>" METHOD="POST">
		<input type="hidden" name="selectCountry" value="<?php print @$selectCountry; ?>">
		<input type="hidden" name="selectState" value="<?php print @$selectState; ?>">
		<input type="hidden" name="selectCity" value="<?php print @$selectCity; ?>">
		
		<tr><td>
		<font face="Verdana, Arial, Helvetica, sans-serif" size="4"> <font size="4">Choose a Country:
		<select name="selectCountry">
		<?php
		foreach ($countryList as $row) {
		print $row;
		}
		?>
		</select> </font>
		</tr></td>
		
		<tr><td>
		<font face="Verdana, Arial, Helvetica, sans-serif" size="4">Choose a State:
		<select name="selectState">
		<?php
		foreach ($cityList as $row) {
		print $row;
		}
		?>
		</select> </font>
		</td></tr>
		
		<tr><td>
		<font face="Verdana, Arial, Helvetica, sans-serif" size="4">Choose a City:
		<select name="selectCity">
		<?php
		foreach ($stateList as $row) {
		print $row;
		}
		?>
		</select> </font>
		</td></tr>
		
		<tr><td>
		<input type="submit" value="NEXT" name="next">
		<input type="submit" value="CLEAR" name="clear">
		</td></tr>
		
	</form>
	<tr><td>
	<FORM name="passData" method=post action="displayList.php">
		<div align="center">
			<center>
				<p><span style="font-family: Verdana, Arial">
					<input type="submit" value="Display List" >
				</span></p>
			</center>
		</div>
	</form>
	</td></tr>	
	<br>
	</td>
	<tr>
		<td>
			<?php
				 include('mainFooter.inc');
			?>
		</td>
	</tr>
	</table>
	
</body>

I’ve solved it! I’m not a Javascript person so I’ve just used form buttons, but you could probably change that so that when someone just clicks on the drop-down menu item it submits the form. But here is what I’ve come up with. It’s at http://www.cbuk.org/adbookv20/triple_dropdown.php by the way:

<?php
  if ($stage == "1") {
    session_start();
    session_register('Country');
  } elseif ($stage == "2") {
    session_start();
    session_register('Country');
    session_register('State');
  } elseif ($stage == "3") {
    session_start();
    session_register('Country');
    session_register('State');
    session_register('City');
  }

  include('includes/dbConnect.php');
?>

<html>

<body>

<form name="step1" action="triple_dropdown.php?stage=1" method="post">
<select name="Country">
	<?php
	  $country = @mysql_query("SELECT * FROM Locations WHERE Country = '' AND State = '' ORDER BY PlaceName") or die ("<p>ERROR!</p>");
	  while ($row = @mysql_fetch_array($country)) {
	    echo("<option value=\\"" . $row["PlaceName"] . "\\">" . $row["PlaceName"]);
	  }
	?>
</select> <input type="submit" value="-->">
</form>

<?php
  if ($stage >= 1) {
    echo("<form name=\\"stage2\\" action=\\"triple_dropdown.php?stage=2\\" method=\\"post\\"><select name=\\"State\\">");
    $state = @mysql_query("SELECT * FROM Locations WHERE Country = '$Country' AND State = '' ORDER BY PlaceName") or die ("<p>ERROR!</p>");
    while ($row = @mysql_fetch_array($state)) {
      echo("<option value=\\"" . $row["PlaceName"] . "\\">" . $row["PlaceName"]);
    }
    echo("</select> <input type=\\"submit\\" value=\\"-->\\"></form>");
  }
?>

<?php
  if ($stage >= 2) {
    echo("<form name=\\"stage3\\" action=\\"triple_dropdown.php?stage=3\\" method=\\"post\\"><select name=\\"City\\">");
    $city = @mysql_query("SELECT * FROM Locations WHERE Country = '$Country' AND State = '$State' ORDER BY PlaceName") or die ("<p>ERROR!</p>");
    while ($row = @mysql_fetch_array($city)) {
      echo("<option value=\\"" . $row["PlaceName"] . "\\">" . $row["PlaceName"]);
    }
    echo("</select> <input type=\\"submit\\" value=\\"-->\\"></form>");
  }
?>

<p><b>
<?php
  if ($stage == "3") {
    echo($City . ", " . $State . ", " . $Country);
  }
?>
</b></p>

</body>

</html>

Hope this is what you wanted?

  • Will

Oh, and I used the following table as an example:


------------------------------------------------------------
|  ID  |     PlaceName     |   Country   |      State      |
------------------------------------------------------------
|   1  | England           |             |                 |
|   2  | USA               |             |                 |
|   3  | Northamptonshire  | England     |                 |
|   4  | Oxfordshire       | England     |                 |
|   5  | Buckinghamshire   | England     |                 |
|   6  | Northampton       | England     | Northamptonshire|
|   7  | Roade             | England     | Northamptonshire|
|   8  | Towcester         | England     | Northamptonshire|
|   9  | Florida           | USA         |                 |
|  10  | Ohio              | USA         |                 |
|  11  | Fort Lauderdale   | USA         | Florida         |
|  12  | Miami             | USA         | Florida         |
------------------------------------------------------------

For example: Roade is a City in the State of Northamptonshire, which is in the Country of England!

Get in contact with me if this is or isn’t what you were looking for.

  • Will

Will,

I tried your example but it’s not working quite right.
If I choose “England” and do a select, I only get states
for the US, and it relists England as the chosen country.
Even if I choose USA and Florida, I get no cities, and the
display goes back to the original list.

What I’m trying to do is Select a Distinct Country,
then keep that country in the display and only list the
states in the selected country. Then follow the same
pattern with the cities. When the screen is redisplayed, I
want it to display the original country selected, the
original state selected and a list of the cities for that
state only, so that when I change pages and do the display
list I am only passing the specified city, state and
country name.

The code that I started, finds the Distinct countries but
when I hit the Next button, it puts the country back to the
last one in the list and doesn’t give me a list of states.

Thanks for trying,

CC

I finally got this working so I thought I’d put it
in here. This is using PHP version 4.0.6, so I can’t
use the new globals ($_POST, etc.)


&lt;?php
  if ($stage == "0"){
     session_start();
	 unset($HTTP_SESSION_VARS['Country']);
	 unset($HTTP_SESSION_VARS['State']);
	 unset($HTTP_SESSION_VARS['City']);
	 session_destroy();
	 }
  if ($stage == "1") {
    session_start();
    session_register('Country');
  } elseif ($stage == "2") {
    session_start();
    session_register('Country');
    session_register('State');
  } elseif ($stage == "3") {
    session_start();
    session_register('Country');
    session_register('State');
    session_register('City');
  }

   include('db.php');
   mysql_select_db($dbname);
?&gt;

&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Find Country&lt;/title&gt;&lt;meta name="Microsoft Border" content="b, default"
&lt;meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"&gt;
&lt;/head&gt;

&lt;body&gt;
&lt;table border="1" width="950" cellpadding="5"&gt;

  &lt;tr&gt;
  	&lt;td width="150" valign="top" bgcolor="#33CCFF"&gt;
	&lt;?
        include('mainMenu.inc');
    ?&gt;
	&lt;/td&gt;
    &lt;td valign="top" background="images/blue.jpg"&gt;
		&lt;?
	      include('findHeader.inc');
		?&gt;
		&lt;table width="800" cellpadding="5"&gt;
		&lt;p align="left"&gt;&lt;font size="2" face="Verdana, Arial, Helvetica, sans-serif"&gt;
		Select the name of the country, press '---&gt;'. A list of states will appear.
		&lt;br&gt;
		Select the name of the state, press '---&gt;'. A list of cities will appear.
		&lt;br&gt;
		Select the name of the city, press '---&gt;'.
		&lt;/font&gt;&lt;/p&gt;
		&lt;form name="stage1" action="findCountry.php?stage=1" method="post"&gt;
		&lt;font face="Verdana, Arial, Helvetica, sans-serif" size="2"&gt; &lt;font size="4"&gt;Choose a Country:
		&lt;select name="Country"&gt;
		&lt;?php
		    $country = @mysql_query ("SELECT DISTINCT (Country) FROM `Customer` ORDER BY Country ASC");
			      while ($row = @mysql_fetch_array($country))
				  {
				        echo("&lt;option value=\\"" . $row["Country"] . "\\"&gt;" . $row["Country"]);
				  }
		?&gt;
		&lt;/select&gt;
		&lt;input type="submit" value="---&gt;"&gt;
		&lt;/font&gt;
		&lt;/form&gt;
		
		&lt;?php
		    if ($stage &gt;= 1)
			{?&gt;
			&lt;form name="stage2" action="findCountry.php?stage=2" method="post"&gt;
			&lt;font face="Verdana, Arial, Helvetica, sans-serif" size="4"&gt;Choose a State:
			&lt;select name="State"&gt;
			&lt;?php
				$state = @mysql_query("SELECT DISTINCT (StateProv) FROM Customer WHERE Country = '$Country' ORDER BY StateProv ASC");
				    while ($row = @mysql_fetch_array($state))
					{
						echo("&lt;option value=\\"" . $row["StateProv"] . "\\"&gt;" . $row["StateProv"]);
					}?&gt;
			&lt;/select&gt;
			&lt;input type="submit" value="---&gt;"&gt;&lt;/font&gt;&lt;/form&gt;
			&lt;?php
			}?&gt;
			
			&lt;?php
			    if ($stage &gt;= 2)
				{?&gt;
				&lt;form name="stage3" action="findCountry.php?stage=3" method="post"&gt;
				&lt;font face="Verdana, Arial, Helvetica, sans-serif" size="4"&gt;Choose a City:
				&lt;select name="City"&gt;
				&lt;?php
				    $city = @mysql_query("SELECT DISTINCT (City) FROM Customer WHERE StateProv = '$State' AND Country = '$Country'");
					    while ($row = @mysql_fetch_array($city))
						{
						      echo("&lt;option value=\\"" . $row["City"] . "\\"&gt;" . $row["City"]);
						}?&gt;
				&lt;/select&gt;
				&lt;input type="submit" value="---&gt;"&gt;&lt;/font&gt;&lt;/form&gt;
				&lt;?php
				}?&gt;
				&lt;p&gt;
				&lt;?php
					if ($stage == "3")
					{?&gt;
						&lt;font face="Verdana, Arial, Helvetica, sans-serif" size="3"&gt;You have chosen:&lt;/font&gt;
						&lt;b&gt;
						&lt;font color="#FF0000"&gt;
						&lt;?php
						echo($City . ", " . $State . ", " . $Country);
						?&gt;
						&lt;/font&gt;
						&lt;/b&gt;
						&lt;font face="Verdana, Arial, Helvetica, sans-serif" size="3"&gt;
						&lt;br&gt;
						&lt;br&gt;If this is correct press the &lt;b&gt;"Display List"&lt;/b&gt; button to continue.
						&lt;br&gt;
						&lt;br&gt;If this in not correct press the &lt;b&gt;"Clear"&lt;/b&gt; button to start again.
						&lt;br&gt;
						&lt;/font&gt;
                        &lt;FORM name="passData" method="post" action="displayList.php?&lt;?php $HTTP_POST_VARS['City'];$HTTP_SESSION_VARS['State']; $HTTP_SESSION_VARS['Country'];?&gt;"&gt;
						&lt;div align="center"&gt;
							&lt;center&gt;
								&lt;p&gt;&lt;span style="font-family: Verdana, Arial"&gt;
									&lt;input type="submit" value="Display List"&gt;
								&lt;/span&gt;&lt;/p&gt;
							&lt;/center&gt;
						&lt;/div&gt;
						&lt;/form&gt;
						&lt;?php
					}?&gt;
				&lt;/td&gt;&lt;/tr&gt;
				&lt;/p&gt;
				&lt;br&gt;
				&lt;tr&gt;&lt;td&gt;
				&lt;FORM name="clearData" action="findCountry.php?stage=0" method="post"&gt;
				&lt;div align="center"&gt;
					&lt;center&gt;
						&lt;p&gt;&lt;span style="font-family: Verdana, Arial"&gt;
						&lt;input type="submit" value="CLEAR" name="clear"&gt;
						&lt;/span&gt;&lt;/p&gt;
					&lt;/center&gt;
				&lt;/div&gt;
				&lt;/form&gt;
				&lt;/td&gt;&lt;/tr&gt;
		&lt;/td&gt;
		&lt;td&gt;
			&lt;?php
				 include('mainFooter.inc');
			?&gt;
		&lt;/td&gt;
	&lt;/tr&gt;
	&lt;/table&gt;	
&lt;/body&gt;

Hope this is helpful to someone else.

CC

is there php a way to do this without the –> buttons, i’m pretty sure this can’t be done with php but i would really love to do this without javascript, buttons or reloading :wink:

:water

Trying to follow this thread; in the last code, what would the findCountry.php code look like?

Thanks