Reputation: 117
I am using PHP and HTML to construct a HTML table that generates with a PHP while loop. I am populating a HTML dropdown menu with all of the distinct portfolio names in my mySQL database. To do this I am doing:
$query2 = "SELECT DISTINCT PORT FROM CELP";
$result2 = mysql_query($query2) or die (mysql_query($default));
if ($result2)
{
{
echo "<select id='port' name='port'>";
while ($col = mysql_fetch_array($result2)) {
echo "<option value='" . $col[0] . "'>" . $col[0] . "</option";
}
echo "</select>";
} }
This works but whenever I submit my form the dropdown value I selected resets to the default first value. How can I put the "selected" tag in the option that was last submitted, and that one only. P.S. I use $_GET and the variable name for that is port, so it shows the currently selected portfolio in the URL.
Upvotes: 3
Views: 242
Reputation: 13232
Do this:
while ($col = mysql_fetch_array($result2)) {
if(shouldBeSelected)
{
echo "<option selected="selected" value='" . $col[0] . "'>" . $col[0] . "</option";
}
else
{
echo "<option value='" . $col[0] . "'>" . $col[0] . "</option";
}
}
Do it for the one that should be selected. You just need to use the selected
property.
Upvotes: 2