-4

I have a problem about data stored in database. I want to select data that was fetch from database and show in drop down menu. for example I have "age" field in database and I have drop down menu.and I stored "20" in this field in database and when I fetch this I want "20" to be selected in select tag.(value="20" selected="selected') and user can edit this.It means user can click on drop down menu and sees other options but the selected option is the data that was fetch from database.

I tried this but it doesn't work:

   <select> 
     <option <? if($detail['age']==19) {?> selected="selected" <? } ?> >19</option>
     <option <? if($detail['age']==20) {?> selected="selected" <? } ?> >20</option>
     <option <? if($detail['age']==21) {?> selected="selected" <? } ?> >21</option>
   </select>

HELP ME!!!

sabbagh
  • 23
  • 5

2 Answers2

0

Quick script:

$res=$db->query("SELECT age FROM sometable WHERE something");
$html="<select name=\"something\" size=\"3\">";
while($row=$res->fetch_object())
{
    $html.="<option value=\"" . htmlentities($row->age) . "\">" . htmlentities($row->age) . "</option>";
}
$html.="</select>";

Adjust as you want, you need to replace all the some... with the appropirate values.

Lorenz
  • 2,093
  • 3
  • 18
  • 18
  • I'm beginner!what does the loop mean?how it work?can you explain?thanks! – sabbagh Jun 17 '13 at 19:23
  • I query the MySQL table for the values and then loop through them, every row one loop. At every loop I add an option to the html code. At the beginning and at the end I add the opening and closing elements for HTML. htmlentities is there for special characters that they don't mess up your HTML code. – Lorenz Jun 17 '13 at 19:38
0
<select>
    <option <?php if($detail['age']==19) {?> selected="selected" <phh? } ?> >19</option> 
    <option <?php if($detail['age']==20) {?> selected="selected" <php? } ?> >20</option>
    <option <?php if($detail['age']==21) {?> selected="selected" <php? } ?> >21</option>
</select>
Luc M
  • 15,742
  • 26
  • 71
  • 88
nosdalg
  • 589
  • 1
  • 4
  • 22