mysql - PHP Bootstrap multi select options -


in code using php populates bootstrap multi selectpicker mysql database problem selects last option instead of multiple options, don't know missing in it? here my code

function multibindcombo($tablenames, $columnnames1, $columnnames2, $comboname, $selectedopt) {     global $conn;      $sql="select ". $columnnames1. ", " . $columnnames2 . " ". $tablenames;     $result = mysqli_query($conn, $sql);     if( ! $result ) {         echo mysql_error();         exit;     }     echo '<select class="selectpicker form-control" data-live-search="true" name="' . $comboname . '" multiple="multiple">';     $array = explode(',', $selectedopt);     while ($row=mysqli_fetch_array($result)) {             foreach ($array $select_option){             if($row[$columnnames1] == $select_option) {                 $print_selected = 'selected';             } else {                 $print_selected = '';             }             echo $select_option;             }         echo '<option data-tokens="' . $row[$columnnames1] . '" value="' . $row[$columnnames1] . '"' .$print_selected. '>' . $row[$columnnames2] . '</option>';     }     echo '</select>'; } 

to selected values in multiselect need use name attribute []:

echo '<select class="selectpicker form-control" data-live-search="true" name="' . $comboname . '[]" multiple="multiple">'; 

after can iterate on $_post[$comboname] foreach.

update:

let's closer code here:

while ($row=mysqli_fetch_array($result)) {     foreach ($array $select_option){          // iterate on every value of array, in end         // `$print_selected` defined depending on value of          // last `$select_option`          if($row[$columnnames1] == $select_option) {             $print_selected = 'selected';         } else {             $print_selected = '';         }          // remove this. why echo `$select_option`?         echo $select_option;     }     echo '<option data-tokens="' . $row[$columnnames1] . '" value="' . $row[$columnnames1] . '"' .$print_selected. '>' . $row[$columnnames2] . '</option>'; } 

rewrite as:

while ($row=mysqli_fetch_array($result)) {     $print_selected = '';      foreach ($array $select_option){         if($row[$columnnames1] == $select_option) {             $print_selected = 'selected';              // break `foreach` found right item             break;         }     }     // if right item not found - `$print_selected` empty      echo '<option data-tokens="' . $row[$columnnames1] . '" value="' . $row[$columnnames1] . '"' .$print_selected. '>' . $row[$columnnames2] . '</option>'; } 

Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - Z-index in d3.js -