PHP Variable in Drop Down Menu
-
30-06-2021 - |
Question
Hello I have a Query running on a page right now.
Ultimately I need the Country Code(Variable) to be selectable via Drop down menu so the query runs with with the selected Country Code(Variable.)
I would also like the Country Code to remain selected even if I go to another page so the query automatically runs with the preselected variable.
Thanks
Solution
Your form should read something similar to:
<form name="country_list" method="POST" action="http://examplewebsite.com/script.php" target="_blank">
Country: <select name="Country" tabindex="1">
<optgroup label="Continent">
<option value="Country 1">Country 1</option>
<option value="Country 2">Country 2</option>
<option value="Country 3">Country 3</option>
</optgroup>
</select>
<input type="submit" value="Filter" />
</form>
To input the selected country you would need to use $_POST[]
<?php
$selected = $_POST['Country'];
?>
A long winded, but fairly simple approach to ensuring the selected country remains selected would be to each option as:
<option value="Country 1" <? if($selected == 'Country 1'){ echo 'selected="selected"';} ?> >Country 1</option>
<option value="Country 2" <? if($selected == 'Country 2'){ echo 'selected="selected"'; ?> }>Country 2</option>
I realise for individual countries this could take a long while, but it should work - your problem is needing the 'selected="selected"' expression within the opening tag of each option on the list.
This would only work if you reloaded the page from within the script - for example if you were error-checking the whole form and wanted to preserve the submitted results. If you are transitting to an entirely different page then a cookie would be one way to store the data, there are security issues and legal issues, especially in Europe, governing the use of cookies, however.