如何在多个选择(如boostrap-select)中保留所选值

时间:2018-08-04 04:52:33

标签: php html bootstrap-4 bootstrap-select

我要保留提交表单后选择的值。

<select name="student[]" class="selectpicker" multiple title="Click here.." data-width="auto" data-live-search="true" required>
  <?php 	
    if (isset($_POST['submit'])){
    $selected = $_POST['studname'];
    $qry = "Select studtbl.stud_id,concat(studtbl.fname,' ', 
    substring(studtbl.mname, 1,1),'. ',studtbl.lname) as Name from studtbl";
		$result = mysqli_query($conn, $qry);
		while($row = mysqli_fetch_array($result))
		{
		extract($row);
		echo '<option value="'.$stud_id.'" '.(($stud_id == 
        $selected)? 'selected="selected"':"" >'.$Name.'</option>';
		} 
	}else{
    $qry = "Select studtbl.stud_id,concat(studtbl.fname,' ', 
    substring(studtbl.mname, 1,1),'. ',studtbl.lname) as Name from studtbl";
				$result = mysqli_query($conn, $qry);
				while($row = mysqli_fetch_array($result))
				{
					extract($row);
					echo '<option value="'.$stud_id.'" >'.$Name.'</option>';
				} 
	}
    ?>
</select>
<input type='submit' class="btn btn-primary" name='submit' value='Create 
     Account' />

我的问题是提交后没有保留

1 个答案:

答案 0 :(得分:0)

<select name="student[]" class="selectpicker" multiple title="Click here.." data-width="auto" data-live-search="true" required>
  <?php     
    if (isset($_POST['submit'])){
    $selected = $_POST['student']; // <---- multi-selects come in as Array
    $qry = "Select studtbl.stud_id,concat(studtbl.fname,' ', 
    substring(studtbl.mname, 1,1),'. ',studtbl.lname) as Name from studtbl";
        $result = mysqli_query($conn, $qry);
        while($row = mysqli_fetch_array($result))
        {
        extract($row);
        // if the current ID is inside the POST-ed Array - mark as SELECTED
        echo '<option value="'.$stud_id.'" '.(in_array($stud_id, $selected) ? 'selected="selected"': "").'>'.$Name.'</option>';
        } 
    }else{
    $qry = "Select studtbl.stud_id,concat(studtbl.fname,' ', 
    substring(studtbl.mname, 1,1),'. ',studtbl.lname) as Name from studtbl";
                $result = mysqli_query($conn, $qry);
                while($row = mysqli_fetch_array($result))
                {
                    extract($row);
                    echo '<option value="'.$stud_id.'" >'.$Name.'</option>';
                } 
    }
    ?>
</select>
<input type='submit' class="btn btn-primary" name='submit' value='Create 
     Account' />