【问题标题】:Checkbox values are lost when form submitted with errors in PHP当表单在 PHP 中出现错误时,复选框值会丢失
【发布时间】:2016-12-18 18:06:31
【问题描述】:

我在我的项目中使用 PHP 和 MYSQLI。我有一个表单,其中包含一个文本输入字段和三个复选框。当用户选中三个选项中的两个并提交表单而不填写文本输入字段时,我会显示错误。

现在我想要实现的是,当显示错误时,用户选中的特定复选框不应该被取消选中。请理解,表单中所有复选框的类别字段都是相同的。

我的表单示例如下:

<?php if(isset($_POST['submit'])) {    
    $full_name=$db->real_escape_string($_POST["full_name"]);
    $checkbox = implode(',', $_POST["fruits"]);

    if(empty($checkbox)) {
        $errors = 'Please choose at least one fruit.';
    }

    if(!isset($errors)) {
        // I am inserting the data
    } else {
        $errors;
    }
} 
?>

<form method="post" action="add.php">
<input type="text" name="full_name">
<input type="checkbox" name="fruits[]" value="Apple">
<input type="checkbox" name="fruits[]" value="Banana">
<input type="checkbox" name="fruits[]" value="Carrot">
<input type="submit" name="submit" value="Submit">
</form>

【问题讨论】:

  • 能贴出PHP代码吗?
  • 我已经更新了我的代码以匹配你的 PHP 代码。

标签: php forms checkbox submit


【解决方案1】:

执行in_array() 检查以查看水果是否在数组中,然后回显checked="checked" 以使其选中该框(再次)。

<?php
if( isset($_POST['submit']) ) {
    $errors = array();

    $full_name = $db->real_escape_string($_POST["full_name"]);
    //Initialize empty array (In case fruits isn't sent, if they didn't check any boxes)
    $fruits = array();

    //We get an array? Cool, set it to $fruits
    if ( isset($_POST['fruits']) && is_array($_POST['fruits']) ) {
        $fruits = $_POST['fruits'];
    }

    if ( empty($full_name) ) {
        $errors[] = 'Please enter your name.';
    }

    if( empty($fruits) ) {
        $errors[] = 'Please choose at least one fruit.';
    }

    if( empty($errors) )
    {
        //Change $fruits into a string
        $fruits = implode(', ', $fruits);
        // I am inserting the data
    } else {
        foreach ( $errors as $error )
        {
            echo '<p class="error">', $error, '</p>';
        }
    }
}

?>

<form method="post" action="add.php">
    <input type="text" name="full_name" value="<?=htmlspecialchars($_POST['full_name'])?>" />
    <input type="checkbox" name="fruits[]" value="Apple"<?=(in_array('Apple', $fruits) ? ' checked="checked"' : '') ?> />
    <input type="checkbox" name="fruits[]" value="Banana"<?=(in_array('Banana', $fruits) ? ' checked="checked"' : '') ?> />
    <input type="checkbox" name="fruits[]" value="Carrot"<?=(in_array('Carrot', $fruits) ? ' checked="checked"' : '') ?> />
    <input type="submit" name="submit" value="Submit" />
</form>

【讨论】:

  • 感谢 FrankerZ 的快速回复,这解决了我的问题并按预期工作。再次感谢,祝您有美好的一天。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-29
  • 2016-11-12
  • 1970-01-01
相关资源
最近更新 更多