views:

166

answers:

2

I'm fairly sure there has to be a simple solution to my problem, but I am a new web developer and can't quite figure it out.

On my page I have a combo box whose values are filled from my database. When the user submits the form, how to I go about converting those values back to the record numbers in the database?

Up to now I have been just doing a sort of reversed lookup in my database to try to get the record's ID. This has quite a few obvious flaws and I am sure that there has to be a better way. I am used to MS Forms combo boxes where the record data and ID are never separated. But in the case of a web form, I have no way to do multiple columns in the combo box like I am used to.

Thanks! Jeff

+2  A: 

The option element that is used to render the options in a select has both a name and a value property -

<option value="23434">Name of item with id 23434</option>

In this case its the value that will be posted to the server and so you don't need to do a reverse lookup to get the id from the name.

Sean Kinsey
I knew there had to be a simple solution! Thanks.
Icode4food
Simple and easy, sometimes HTML is not all that bad.
Marthinus
A: 

a generic function to build select options from an array of sql results or whatever.

<?php
function buildOptions( $options, $value, $label ){

    foreach ( $options as $option ):    
    echo '<option value="'.$option[ $value ].'">'.$option[ $label ].'</option>'."\n";
    endforeach;
}
?>

usage...

<select name="dropdown">
<?php
    $arr = array(
       array( 'id'=>1, 'name'=>'item 1'),
        array( 'id'=>2, 'name'=>'item 2'),
        array( 'id'=>3, 'name'=>'item 3'),
        array( 'id'=>4, 'name'=>'item 4')
      );

    buildOptions( $arr, 'id', 'name' ); 
?>
</select>
David Morrow