Search code examples
javascriptphphtmldropdown

how to avoid repetition of values in dropdown list while updating in php


I want to update "profile of a user" in php. There is a repetition of one value for two times in dropdown list. for example i take language value='Punjabi' from database but there is also a value placed in dropdown with name of 'Punjabi'. The issue is simply that there is a repetition of value which i don't want.

<?php $result=mysqli_query($conn, "select * from profile where id=$firstPerson");
while($queryArray=mysqli_fetch_array($result)){ ?>  
<select name="language" id="language" >                                      
   <option value='<?php echo $queryArray["language"];?> '> <?php echo $queryArray["language"]; ?></option>
   //for example, the value from database is "Punjabi"                                               
   <option value="Hindi">Hindi</option> 
   <option value="Punjabi">Punjabi</option> 
   <option value="Urdu">Urdu</option>                                            
</select>
<?php } ?>

when a value='Punjabi' from database is selected in dropdown list, the dropdown should not show the value='Punjabi' that is already placed in dropdown. Remember: i have more than 1000 values in my dropdown(html) list.

screenshot


Solution

  • Instead of creating a new option according to the user data, Check if existing options are equal to user data:

    <select name="language" id="language" >                                      
       <option value="Punjabi" <?php if ($queryArray["language"]=="Punjabi"){echo 'selected="selected"'} ?>>Punjabi</option> 
       <option value="Hindi" <?php if ($queryArray["language"]=="Hindi"){echo 'selected="selected"'} ?>>Hindi</option> 
       <option value="Urdu" <?php if ($queryArray["language"]=="Urdu"){echo 'selected="selected"'} ?>>Urdu</option>                                            
    </select>
    

    If there are large number of options and you don't want to hard code these conditions, you can remove the second option using javascript on DOM ready:

    $(document).ready(function(){
        $('option[value="<?php echo $queryArray["language"] ?>"]').eq(1).remove();
    })