I am using php with a dropdown to select data and display the selected item in the dropdown after the page refreshes so have used this code which works.
<select name="select" id="mysort" onchange="select(this.value);">
<option value="5" <?php if($selecting == '5'):?> selected="selected"<?php endif;?>>5 </option>
<option value="6" <?php if($selecting == '6'):?> selected="selected"<?php endif;?>>6 </option>
<option value="7" <?php if($selecting == '7'):?> selected="selected"<?php endif;?>>7 </option>
<option value="8" <?php if($selecting == '8'):?> selected="selected"<?php endif;?>>8 </option>
</select>
I then want to be able to populate the dropdown from a mysql database. This code works:
$sql = "SELECT DISTINCT number FROM files ORDER BY number";
$result = $mysqli->query($sql);
echo '<select name="choose" id="mychoice">';
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo '<option value='.$row["number"].'>'.$row,["number"].'</option>';
}
echo '</select>';
}
I am having trouble with the syntax when I put the two blocks of code together so that the values are populated from the mysql and the selected option displays in the dropdown after the page refreshes. I would be grateful for any help with this.
CodePudding user response:
I think you want this -
while($row = $result->fetch_assoc()) {
echo '<option value="'.$row["number"].'"';
if($selecting == $row["number"]) { echo " selected "; }
echo '>'.$row["number"].'</option>';
}