0
<select name="corequisite">
<option value="" selected="selected">No Corequisite</option>';
$res = mysql_query("SELECT * FROM course");
while($row = mysql_fetch_array($res)){
    echo'<option value="'.$row['Code'].'"';if($row['Code']==$result['corequisite']) echo'  
    selected="selected"';;echo'>'.$row['Name'].'</option>';
}
echo'</select>';

如果没有其他选项与 $result['corequisite'] 匹配,我希望选择“No Corequisite”值。但是表格中的第一项将被选中!

我该如何解决?

它可以通过插入“corequisite”作为第一条记录来修复。一个好方法?

4

2 回答 2

0

我还没有测试过,但这应该可以

<select name="corequisite">
<?php
    // this is your string that will return all your results
    $to_echo = '';

    // this will check if any value inside is selected ( this will be useful later )
    $any_item_selected = false;

    $res = mysql_query("SELECT * FROM course");
    while($row = mysql_fetch_array($res))
    {
        if($row['Code']==$result['corequisite']) // OK! so one item is selected, remember it!
        {
            $to_echo .= '<option selected="selected" value="'.$row['Code'].'">'.$row['Name'].'</option>';
            $any_item_selected = true;
        }
        else
            $to_echo .= '<option value="'.$row['Code'].'">'.$row['Name'].'</option>';
    }

    // Now we can check if anything were selected, and prepend the "No corequisite" option, selected or not! :)
    if( ! $any_item_selected)
        $to_echo = '<option value="" selected="selected">No Corequisite</option>' . $to_echo;
    else
        $to_echo = '<option value="">No Corequisite</option>' . $to_echo;

    echo $to_echo;

?>
</select>
于 2013-09-12T10:31:54.697 回答
0

回答你的最后一个问题,可能是一个不好的方法。

试试这个代码,目前在笔记本电脑上,所以还没有测试过。

<select name="corequisite">
    <?php
    $res = mysql_query("SELECT * FROM course");
    $rows = mysql_num_rows($res);

    if ($rows == 0) 
    { 
         $sel = 'selected';
    } else 
    { 
         $sel = ''; 
    }

    echo '<option '.$sel.' value="">No Corequisite</option>';

    while($row = mysql_fetch_array($res))
    {
        $sel = '';
        if ($row['Code'] == $result['corequisite'])
        {
            $sel = 'selected';
        }
        echo '<option '.$sel.' value="'.$row['Code'].'">' . $row['Name'] . '</option>';
    }
    ?>
</select>
于 2013-09-12T10:37:07.013 回答