Set Selected Option when building HTML Select List in PHP

Wow…you know…the hardest thing about this whole exercise was coming up with a title for this post!

As you’ve gathered from previous entries, I build a lot of my HTML pages in PHP scripts.

When you are building a select list (dropdown, pulldown, picklist) from a database, how do you ensure that the user sees the value that’s in the database?

You could do it using a switch case routine and build your options list in it’s entirety for each option, or you could do it this way.

Scenario, you have an ENUM field in your database that you want to give the user the ability to edit. You also think its very handy for the user to know what’s actually in the database, so you have the select element default to the database value.

Short answer:

Use string replace (str_replace) to add the property selected to the appropriate option.

$options = str_replace('value="G"','value="G" selected',$options);

And now for the long version:

A bunch of code that creates a dataset from a database and puts it in $row[]

$row['ftype'] = 'T';      //you can change these to test the code.
$row['fname'] = 'Text';

$options = '<option value="0">Select a Type</option>';
$options .= '<option value="D">Date</option>';
$options .= '<option value="G">Group</option>';
$options .= '<option value="T">Text</option>';

switch ($row['ftype']) {

    case "D": 

        $options .= str_replace('value="D"','value="D" selected',$options);

   case "G":

      $options .= str_replace('value="G"','value="G" selected',$options);

  case "T":

     $options .= str_replace('value="T"','value="T" selected',$options);

     //nothing to do here

$output = '<html>';
$output .= '<body>';
$output .= '<form id="f1" method="post" action="">';
$output .= '<input type="text" id="f1a" name="f1at" value="'.$row['fname'].'"><br>';

$output .= '<select id="f1b" name="f1b">'.$options.'</select>';
$output .= '</form>';    //pro tip:  type this line immediately after typing the <form> line so you don't forget.

$output .= '</body></html>';
echo $output;

Some of you may have noticed that there is a much easier way to do this if things are as straightforward as in the example.
Simply concatenate the value used in the switch case. This will work great, unless you have additional properties or different formatting in the option tag.

 $options .= str_replace('value="'.$row['ftype'].'"','value="'.$row['ftype'].' selected',$options);

Happy coding…


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s