Shreya
Shreya

Reputation: 103

how to show selected multiple options of drop down in php

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!!!

Upvotes: 1

Views: 10710

Answers (3)

Prasanth Bendra
Prasanth Bendra

Reputation: 32720

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>

Upvotes: 2

Minesh
Minesh

Reputation: 2302

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>
         <?
         }
?>

Upvotes: 1

Venu
Venu

Reputation: 7279

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.

Upvotes: 1

Related Questions