I know there are many questions ask about this one, but I tried a lot from here and for some reason, they did't work for me.
I populate the list from mysqli.:
<select multiple="multiple" name="formCountries[]" size="5" id="keuzeproduct">
<option value="keuze1" disabled selected="selected[]" multiple="multiple">Selecteer Product</option>
<?php
$sql = "SELECT DISTINCT Id, Product FROM metingen group by Product order by Product";
$resultset = mysqli_query($conn, $sql) or die("database error:". mysqli_error($conn));
while( $rows = mysqli_fetch_assoc($resultset) ) {
?>
<option value="<?php echo $rows["Product"];?>" ><?php echo $rows["Product"]; ?></option>
<?php } ?>
</select>
How can I get it so the selected one stays selected after submit?
Get the value that has been selected and pass it to $selected_product
and check with every option you are adding. This should solve your case
<select multiple="multiple" name="formCountries[]" size="5" id="keuzeproduct">
<option value="keuze1" disabled selected="selected[]" multiple="multiple">Selecteer Product</option>
<?php
$selected_product = $your_value_here; //get the selected product from the database on load
$is_selected = "";
$sql = "SELECT DISTINCT Id, Product FROM metingen group by Product order by Product";
$resultset = mysqli_query($conn, $sql) or die("database error:". mysqli_error($conn));
while( $rows = mysqli_fetch_assoc($resultset) ) {
if($selected_product == $rows["Product"]){
$is_selected = "selected";
}
?>
<option value="<?php echo $rows["Product"];?>" <?php echo $is_selected; ?>><?php echo $rows["Product"]; ?></option>
<?php } ?>
</select>
Wrap the option generation with a function:
function makeOption($value)
{
echo "<option value=\"$value\"";
if(isset($_POST['formCountries']) && in_array($value, $_POST['formCountries']))
echo ' selected="selected"';
echo ">$value</option>";
}
Use it in while loop:
while( $rows = mysqli_fetch_assoc($resultset) )
makeOption($rows["Product"]);
Simpy you can do like this for the option script:
<option value="<?php echo $rows["Product"];?>" <?=$rows['Product']=='//your val'?"selected":""?>><?php echo $rows["Product"]; ?></option>
<?php } ?>