Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

selected value get from db into dropdown select box option using php mysql error

Tags:

php

mysql

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 
  }
?>
like image 881
Php Gemini Avatar asked Sep 11 '13 05:09

Php Gemini


People also ask

How get fetch value from dropdown in 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.

How do I get the selected value of dropdown?

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.


2 Answers

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>
like image 95
rakeshjain Avatar answered Sep 20 '22 18:09

rakeshjain


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.

like image 20
independent.guru Avatar answered Sep 21 '22 18:09

independent.guru