0

我正在尝试更新user_pref我的 html 表单中的列。

我有一个看起来像这样的下拉列表(它工作正常):

User pref: <select name="user_pref" size="1" id="user_pref">
<option value="BLUE">Blue</option>
<option value="RED">Red</option>
<option value="YELLOW">Yellow</option>
<?php echo htmlentities($user_pref, ENT_COMPAT, 'utf-8'); ?></select>

我希望能够将默认值设置为用户user_pref在 MySQL 列中已有的值。因此,例如,如果用户 A"Yellow"在其 user_pref 中有,那么我想"Yellow"在更新该用户的首选项时显示。

谁能帮我解决这个问题?

4

1 回答 1

0

这是基本思想...您必须对其进行调整以适应您的需求...

<?php

    // assuming $user_pref is their preference...

    /*
     * create array of possible options...
     * I usually store my options in my database because
     * my applications tend to be dynamic
     * but you can just create a quick array to do the same job
     */
    $arrOptions = array(
        'val1' => 'option1',
        'val2' => 'option2',
        'val3' => 'option3'
    );

    $selected = '';

    print '<select id="user_pref_id">';

    foreach ($arrOptions as $key => $val) {
        // test for $key or $val depending on which makes sense for your application
        $selected = ($key == $user_pref) ? ' selected="selected"' : '';

        printf('<option value="%s"%s>%s</option>', $key, $selected, $val);
    }

    print '</select>';
?>
于 2013-01-29T15:23:43.373 回答