Skip to content
Advertisement

Select values based on database result

I have a form with a multi select which presents the user with a list of groups to chose from,which is then saved in the database. My aim is that when the user wants to edit his information, the groups saved in the database to be selected and the others not to be selected. Please, see my code and advise.

I populate the saved groups to a variable

$groups = array($row['groups']); // This outputs the groupId from the db eg 1,2,3,6

Populate groups to a multi select

<div class="form-group">
     <!-- <label>Church Groups: </label> -->
     <select name="groups[]" class="form-control mandatory" id="groups" multiple="multiple" >
         <?php
             $sql="SELECT ID,UCASE(groupName) AS groupName FROM tblgroups WHERE (congregationId=?)";
             $stmt=mysqli_stmt_init($con);
             mysqli_stmt_prepare($stmt,$sql);
             mysqli_stmt_bind_param($stmt,'i',$congId);
             mysqli_stmt_execute($stmt);
             $result = mysqli_stmt_get_result($stmt);

             while ($row = mysqli_fetch_array($result)) {
                 $selected = "";
                 if(in_array($row['ID'],$groups)){ 
                     $selected = "selected"; 
                 }
                 echo '<option value='.$row['ID'].' '.$selected.'>'.$row['groupName'].'</option>';
             }
          ?>
     </select> 

Thats my code but it doesn’t work. If the first group in the list was saved, only that group is selected all others remain unselected whether in the db or not.

Advertisement

Answer

<div class="form-group">
 <!-- <label>Church Groups: </label> -->
 <select name="groups[]" class="form-control mandatory" id="groups" multiple="multiple" >
     <?php
         $sql="SELECT ID,UCASE(groupName) AS groupName FROM tblgroups WHERE (congregationId=?)";
         $stmt=mysqli_stmt_init($con);
         mysqli_stmt_prepare($stmt,$sql);
         mysqli_stmt_bind_param($stmt,'i',$congId);
         mysqli_stmt_execute($stmt);
         $result = mysqli_stmt_get_result($stmt);
               while ($row = mysqli_fetch_array($result)) {
                   $selected = "";
                   if(in_array($row['ID'],$groups)){ 
                       $selected = "selected"; 
                   }
                   echo '<option value='.$row['ID'].' '.$selected.'>'.$row['groupName'].'</option>';
               }
?>
</select>

Using your code, I have uncommented the line you commented out and introduced a variable that will be blank if the value is not in the group, otherwise it will have the value “selected”, which achieves the same functionality as selected = “selelected”

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement