editing php drop dwn list

suppose i make a drop down menu having value 1, 2, 3, 4, 5, one option can be selected, and selected option is stored in database.
now i create an edit page, how do i display the selected value in the menu and other values in drop down,
for example,
Menu is like
Select One
1
2
3
4
5

and i select 3, this 3 is stored in database, now on the edit page i want to show 3 as already selected,
something like that…

Quote

1 2 3 4 5

I will be very thankful, if someone could help by explaining how do i make option 3 as selected… eg. how i know option 3 is selected and stored in db.

without firing query

If you have a select that goes up numerically from a known value to another value, and you want to have a certain item selected, a function similar to this would work:

[php]/* display_select by http://jsherz.com */
function display_select($select_name, $start, $end, $selected = -1) {
ob_start();
echo ‘’;
for($i = $start; $i < ($end + 1); $i++) {
if($selected != -1 && $selected == $i) {
echo ‘’, $i, ‘’;
} else {
echo ‘’, $i, ‘’;
}
}
echo ‘’;
$result = ob_get_contents();
ob_end_clean();
return $result;
}[/php]

Sample usage:

[php]echo display_select(‘test_select’, 1, 10, 4);[/php]

Even tho our coding is different, you are pretty much spot on. Enjoy reading your responses JSherz :slight_smile:

<?php
  function build_select($name,$options,$selected=NULL)
  {
    $out="<select name=\"$name\">";
    foreach($options as $idx=>$option)
    {
      $out.="<option value=\"$idx\"";
      if($selected===$idx) $out.=" selected";
      $out.=">$option</option>";
    }
    $out.='</select>';
    return $out;
  }
  
  echo build_select('test_select',range(1,5),2);
?>

This is basically the same routine, however we use an array system, with the index to the selected value. This way we can use more than just a range of numbers, reusable :slight_smile: The third parameter is optional as NULL can never be an array index :slight_smile:

That’s a very nice solution you have there! You should post it to the Code Snippets. I’m sure prajakta would be the only one to find it useful!

Sponsor our Newsletter | Privacy Policy | Terms of Service