I need to get selected value from db into select box. please, tell me how to do it. Here is the code. Note: 'options' value depends on the category.
<?php
$sql = "select * from mine where username = '$user' ";
$res = mysql_query($sql);
while($list = mysql_fetch_assoc($res)){
$category = $list['category'];
$username = $list['username'];
$options = $list['options'];
?>
<input type="text" name="category" value="<?php echo '$category' ?>" readonly="readonly" />
<select name="course">
<option value="0">Please Select Option</option>
<option value="PHP">PHP</option>
<option value="ASP">ASP</option>
</select>
<?php
}
?>
php $selection = array('PHP', 'ASP'); echo '<select> <option value="0">Please Select Option</option>'; foreach ($selection as $selection) { $selected = ($options == $selection) ? "selected" : ""; echo '<option '. $selected.
The value of the selected element can be found by using the value property on the selected element that defines the list. This property returns a string representing the value attribute of the <option> element in the list. If no option is selected then nothing will be returned.
I think you are looking for below code changes:
<select name="course">
<option value="0">Please Select Option</option>
<option value="PHP" <?php if($options=="PHP") echo 'selected="selected"'; ?> >PHP</option>
<option value="ASP" <?php if($options=="ASP") echo 'selected="selected"'; ?> >ASP</option>
</select>
The easiest way I can think of is the following:
<?php
$selection = array('PHP', 'ASP');
echo '<select>
<option value="0">Please Select Option</option>';
foreach ($selection as $selection) {
$selected = ($options == $selection) ? "selected" : "";
echo '<option '.$selected.' value="'.$selection.'">'.$selection.'</option>';
}
echo '</select>';
The code basically places all of your options in an array which are called upon in the foreach loop. The loop checks to see if your $options variable matches the current selection it's on, if it's a match then $selected will = selected, if not then it is set as blank. Finally the option tag is returned containing the selection from the array and if that particular selection is equal to your $options variable, it's set as the selected option.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With