Drop Down list to affect another Drop Down list results - using PHP Queries
I have 2 Drop Down menus, both of which get their values from my database.
The 2 drop downs are - Town & County.
Obviously, only certain Towns relate to certain counties.
In order to capture this, they are stored within the database as such:
- Leeds, Morley
- Leeds, Chapel Town
- London, Essex etc..
I need to force the user to choose the County first (which I have done by disable/enable). How ever, on selection of County, I need to refresh the 2nd drop down box with the related 'Town' v开发者_开发技巧alues from the database.
The current code for 'Getting the town' is as such:
echo "<option value='0' >Choose a Town</option>";
$town_se=$_SESSION['town'];
if(isset($county_se)){
$locat=mysql_query("SELECT DISTINCT town_name FROM locations WHERE county_name='$county_se'");
}else{
$locat=mysql_query("SELECT DISTINCT town_name FROM locations ");
}
while($row=mysql_fetch_assoc($locat)){
$town=$row['town_name'];
echo "<option value='$town' >$town</option>";
}
Of course, this doesn't work! Is there a simpler way to replicate the results from the first drop down?
Many thanks in advance.
I'm having a hard time decoding what is going on in your example code. But just to make sure that we are on the same page... PHP is server-side and HTML is client-side. The two cannot interact without something in-between, like a new page-request, javascript or AJAX.
If the data you are presenting is reasonable in size, I would probably just recommend putting all that data in the HTML from the start, but hiding it. That is, create one dropdown for the towns in every county, but hide them all until the user selects a county. (Requires a bit of JavaScript)
Another common solution is to simply submit (and refresh) the page when the user selects a county, thus, you generate a new page with the town dropdown populated with towns for that county. (Requires a bit of JavaScript)
If you want to go really high-tech you could use AJAX and dynamically load the data into the second dropdown when the user selects a county. Although this requires that you have a pretty good understanding of PHP and JS.
精彩评论