问题
I am programming a webpage which uses a select option
dropdown menu to change the language in a MySQL table. There are currently only two language options. I simply want the menu to reflect the current value from the MySQL table.
I retreive the value from MySQL and assign it to variable $valuelanguage
. Here is the php code which I am using, that is not working:
<select id="language" name="language">
<?php
if($valuelanguage=="en")
{
echo '<option selected value="en">English</option>';
echo '<option value="de">Deutsch</option>';
}
else
{
echo '<option value="en">English</option>';
echo '<option selected value="de">Deutsch</option>';
}
?>
</select>
At the moment, if my $valuelanguage
is de then the menu should change to "Deutsch" as the selected option, but instead it stays at "English". Where am I going wrong?
回答1:
The problem is not your code. I tested it on the latest version of Firefox but the refresh (F5
) does not work when I change the value of $valuelanguage
to de
. However, when I press CTRL+F5
, the change takes effect.
I think the answer to this question, with the links it provides, is helpful too.
回答2:
I have changed this function from an if then else to a case switch instead, which functions perfect regardless of refresh. Here is the code:
<?php
$valuelanguage = mysql_query("SELECT value FROM configuration WHERE label='language'");
$lang = mysql_result($valuelanguage, 0);
{
switch ($lang) {
case "en":
echo '<option selected value="en">English</option>';
echo '<option value="de">Deutsch</option>';
break;
case "de":
echo '<option value="en">English</option>';
echo '<option selected value="de">Deutsch</option>';
break;
}
}
?>
I have no idea why the If/then would not work.
回答3:
Use some thing like this and tell me if it works
<select id="language" name="language">
<option value="en" <?php if($valuelanguage=="en"){?> selected<?php }?>>English</option>
<option value="de" <?php if($valuelanguage=="de"){?> selected<?php }?>>Deutsch</option>
</select>
回答4:
<select id="language" name="language">
<option value="en" <?php echo $valuelanguage=="en"? "selected" :"";?> >English</option>
<option value="de" <?php echo $valuelanguage=="de"? "selected" :""; ?>>Deutsch</option>
</select>
try this.... if $valuelanguage!=en or de then select english. so you should be sure $valuelanguage==en or de
来源:https://stackoverflow.com/questions/26658784/php-dropdown-option-selected