Question

I am working on a PHP project as follows

 if( mysql_num_rows( $result ) > 0 ) {
    echo '<select name="officerlist">';
    while ( $rows = mysql_fetch_array ( $result ) ) {                       
       echo '<option>' . $rows['officer'] . '</option>';
       if ($types[ $maxindex ] == $rows['officer']){
        echo ' selected';
       }
    }
        echo '</select>';
}

I am able to populate the query result into the dropdown menu. However, I want to implement it to have a default selected value based on value from another array. (ie if $types[$maxindex] is found in $rows['officer'], it will auto select the value.).

Anyone able to advise?

Thank you and best regards!

Was it helpful?

Solution 2

should be like this,

while ( $rows = mysql_fetch_array ($result) ) {                       

    if ($types[$maxindex] == $rows['officer']){
        echo '<option selected="selected" value="'.$rows['officer'].'">' . $rows['officer'] . '</option>';
    } else {
       echo '<option value="'.$rows['officer'].'">' . $rows['officer'] . '</option>';
    }
   }

OTHER TIPS

try this

if( mysql_num_rows($result)>0 ) {
echo '<select name="officerlist">';
while ( $rows = mysql_fetch_array ($result) ) {                       
if ($types[$maxindex] == $rows['officer']){
    echo '<option selected="selected">' . $rows['officer'] . '</option>';    
}
else
{
    echo '<option>' . $rows['officer'] . '</option>';

}
}
echo '</select>';

You need add the selected attribute inside the <option> tag, like

<option selected='selected'>youroption</option>.

Try this,

if( mysql_num_rows($result)>0 ) {
    echo '<select name="officerlist">';
    while ( $rows = mysql_fetch_array ($result) ) {
        $selected ="";
        if ($types[$maxindex] == $rows['officer']){
            $selected = ' selected="selected" ';
        }
        echo '<option '.$selected.'>' . $rows['officer'] . '</option>';

    }
    echo '</select>';
}
while ( $rows = mysql_fetch_array ($result) ) {                       

    if ($types[$maxindex] == $rows['officer']){
        echo '<option SELECTED>' . $rows['officer'] . '</option>';
    } else {
       echo '<option>' . $rows['officer'] . '</option>';
    }
   }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top