在我的代码中,我正在使用PHP
填充selectpicker
数据库中的引导程序多MySQL
,但问题是它只选择最后一个选项而不是多个选项,我不会&#39我不知道我错过了什么?这是我的代码
function MultiBindCombo($tablenames, $columnnames1, $columnnames2, $comboname, $selectedopt) {
global $conn;
$sql="SELECT ". $columnnames1. ", " . $columnnames2 . " FROM ". $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 as $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>';
}
答案 0 :(得分:3)
要获取多选中的所有选定值,您需要将name
属性与[]
一起使用:
echo '<select class="selectpicker form-control" data-live-search="true" name="' . $comboname . '[]" multiple="multiple">';
之后,您可以使用$_POST[$comboname]
迭代foreach
。
<强>更新强>:
让我们仔细看看你的代码:
while ($row=mysqli_fetch_array($result)) {
foreach ($array as $select_option){
// You iterate over every value of array, so in the end
// `$print_selected` is defined depending on value of the
// last `$select_option`
if($row[$columnnames1] == $select_option) {
$print_selected = 'selected';
} else {
$print_selected = '';
}
// remove this. Why you echo `$select_option`?
echo $select_option;
}
echo '<option data-tokens="' . $row[$columnnames1] . '" value="' . $row[$columnnames1] . '"' .$print_selected. '>' . $row[$columnnames2] . '</option>';
}
将其重写为:
while ($row=mysqli_fetch_array($result)) {
$print_selected = '';
foreach ($array as $select_option){
if($row[$columnnames1] == $select_option) {
$print_selected = 'selected';
// break `foreach` as you found the right item
break;
}
}
// if right item is not found - `$print_selected` is empty
echo '<option data-tokens="' . $row[$columnnames1] . '" value="' . $row[$columnnames1] . '"' .$print_selected. '>' . $row[$columnnames2] . '</option>';
}