Your code attempts to add a "selected" if the current $id
equals $bamid
, but what it does in all other cases? It doesn't know, so it throws a warning.
It still works, because undefined strings are rendered as empty strings in PHP, but it would be better to state this explicitly.
<?
// BTW, this opening tag would be better as <?php
// #include standard recommendation on moving to PDO instead of deprecated MySQL
// support
while ($row=mysql_fetch_array($result))
{
$id = $row['id'];
$name = $row['name'];
$selected = array($bamid => "selected");
$options.="<option value = \"$id\" $selected[$id]>".$name.'</option>';
}
You can do it like this:
$selected = ($id == $bamid) ? 'selected="selected"' : '';
$options.="<option value=\"$id\" $selected>$name</option>";
or, maybe making for more readable code at the expense of duplication:
if ($id == $bamid) {
$options.= <<<OPTION_SELECTED
<option value="{$id}" selected="selected">{$name}</option>
OPTION_SELECTED;
} else {
$options.= <<<OPTION_NOT_SELECTED
<option value="{$id}">{$name}</option>
OPTION_NOT_SELECTED;
}
If you do this a lot, you might want to write a utility function that takes an array of keys
and values
and zero or more selected keys/values, and returns the HTML for a combo box list of options. This would lead to
$optarr = array();
while ($row=mysql_fetch_array($result))
{
$id = $row['id'];
$name = $row['name'];
$optarr[$id] = $name;
}
mysql_free_result($result);
$options = htmlOptions($optarr, $bamid);