Populate Dropdown From Database And Set Default Value
Right now I have a working solution for populating an HTML
Solution 1:
You can do that like given below:
<?php
$result = $mysqli->query("select * from listoption");
$id = ($_GET['id'])? $_GET['id'] : '';
echo "<selectid='list'name='list'>";
while ($row = $result->fetch_assoc()) {
$listoption_item = $row['listoption_item'];
$sel = ($id == $row['id'])? 'selected="selected"':'';
echo '<optionvalue="'.$listoption_item.'" '.$sel.'>'.$listoption_item.'</option>'; // $sel will deside when to set `selected`
}
echo "</select>";
?>
Solution 2:
You can rewrite the code as follows:
<?php$id = $_GET['id'];
$select = "";
$result = $mysqli->query("select * from listoption");
echo"<select id='list' name='list'>";
while ($row = $result->fetch_assoc()) {
$row_id = $row['ID'];
if($row_id == $id){
$select = "selected";
}
$listoption_item = $row['listoption_item'];
echo'<option value="'.$listoption_item.'" selected="'.$select.'">'.$listoption_item.'</option>';
}
echo"</select>";
?>
Solution 3:
Use the following code:-
<?php$selectedId = isset($_GET['id'])?$_GET['id']:0;
$result = $mysqli->query("select * from listoption");
echo"<select id='list' name='list'>";
while ($row = $result->fetch_assoc()) {
$listoption_item = $row['listoption_item'];
echo'<option value="'.$listoption_item.' .(($selectedId>0)?:" selected ":"").'">'.$listoption_item.'</option>';
}
echo "</select>";
?>
Post a Comment for "Populate Dropdown From Database And Set Default Value"