如何“记住”rdquo;在PHP中选择的表单值?

如果用户未能通过表单验证,那么为了使它们更容易,我们可以这样做:
if(isset($_POST['submit'])) {
    $email = $_POST['email'];
    //....
}

<input type="text" name="phone" value="<?php echo $phone; ?>" />
<input type="text" name="email" value="<?php echo $email; ?>" />
...
因此,在这种情况下,如果用户因为输入了电子邮件但未输入电话号码而未通过验证,那么当提交页面刷新并警告他们丢失了电话时,电子邮件(他们确实已填写)已经在其中放置并且不需要用户重新输入。 但是,如何“记住”用户为select,radio和checkbox输入选择的值?     
已邀请:
它的工作方式相同,但还需要更多工作:
<select name="whatever">
  <option value="Apple">Apple</option>
  <option value="Banana" selected="selected">Banana</option>
  <option value="Mango">Mango</option>
</select>
Banana is selected here.

<input type="checkbox" name="fruits[]" value="banana" /> Banana
<input type="checkbox" name="fruits[]" value="mango" checked="checked" /> Mango
<input type="checkbox" name="fruits[]" value="apple" checked="checked" /> Apple
Mango and Apple are checked here
因此,基本上,在生成表单时,将
selected="selected"
checked="checked"
添加到相应的字段中。 另一种选择是在页面加载并准备好进行DOM操作后,使用类似jQuery的东西来进行这些选择。这样,您可以轻松地将所有更改放在一个位置,而无需验证代码。当然现在有一个缺点,你需要加载jQuery,你的用户将需要JS一个。     
这是一些示例代码。
<?php
$options = array('option1' => 'Option 1', 'option2' => 'Option 2', 'option3' => 'Option 3');
$myselect = 'option2';
?>
<select name="myselect">
<?php 
foreach($options as $key => $value) {
    echo sprintf('<option value="%s" %s>%s</option>', $key, $key == $myselect ? 'selected="selected"' : '', $value);
}
?>
</select>
如果你经常做这样的事情,它在函数中更加整洁,或者你甚至可以创建一个Form类助手。 这是一个基本的选择功能:
<?php
function form_select($name, $options, $selected) {
    $html = sprintf('<select name="%s">', $name);
    foreach($options as $key => $value) {
        $html .= sprintf('<option value="%s"', $key);
        if ($selected == $key)
            $html .= ' selected="selected"';
        $html .= sprintf('>%s</option>', $value);
    }
    $html .= '</select>';
    return $html;
}
然后,只需调用即可创建任何选择:
echo form_select('myselect', $options, $selected);
您可以轻松地使该函数处理诸如样式,类和id之类的更多属性。     
<input type="radio" name="xxxx" <?php if ($xxx == 'VALUE') echo "checked="checked""; ?>" />
与select中的选项类似     

要回复问题请先登录注册