问题
First see my code.
<select multiple name='assign_to[]'>
<?
$result_10 = mysql_query("select * from login_users") or die(mysql_error());
while($row_10 = mysql_fetch_object($result_10))
{
echo "<option value=".$row_10->user_id.">".$row_10->username."</option>";
}
?>
</select>
I am able to get value when page is submitted no issue with this but my problem is :
When page is submitted I am redirecting to the same page then I want that options which are selected before submitting the form will seen selected after page is submitted.
What PHP code is to written there. What I did for single selected drop down as :
<?
while($row_10 = mysql_fetch_object($result_10))
{
?>
<option <?=$row_10->user_id==$_POST['assign_to']?'selected':''?> value="<?=$row_10->user_id?>"><?=$row_10->username?></option>
<?
}
?>
Hope you are getting my question ?
Thanks!!!
回答1:
if(in_array($row_10->user_id,$_POST['assign_to'])){echo "selected"}else{echo ""}
As your $_POST['assign_to'] is an array i guess this will work.
OR you can use conditional operators :
<option <?= in_array($row_10->user_id,$_POST['assign_to']) ? 'selected' : ''?> value="<?=$row_10->user_id?>"><?=$row_10->username?></option>
回答2:
Use in_array
<option <?=$row_10->user_id=$_POST['assign_to']?'selected':''?> value="<?=$row_10->user_id?>"><?=$row_10->username?></option>
replace with
<option <?= (in_array($row_10->user_id,$_POST['assign_to'])) ? 'selected' : ''?> value="<?=$row_10->user_id?>"><?=$row_10->username?></option>
You will get the selected values as an array, so check the value exists in an array.
回答3:
As you are using multiple select box, you will receive array of values in POST variable, so you need to check if the value exists in that array instead of equating it
You can try in_array function as shown below:
<?
while($row_10 = mysql_fetch_object($result_10))
{
?>
<option <?=in_array($row_10->user_id,$_POST['assign_to'])?'selected':''?> value="<?=$row_10->user_id?>"><?=$row_10->username?></option>
<?
}
?>
来源:https://stackoverflow.com/questions/14812056/how-to-show-selected-multiple-options-of-drop-down-in-php