在PHP中提交错误的表单时,复选框值会丢失

时间:2016-08-11 20:48:40

标签: php forms checkbox submit

我正在为我的项目使用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>

1 个答案:

答案 0 :(得分:0)

执行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>