user2945468 user2945468 - 3 months ago 7
PHP Question

Checkbox values are lost when form submitted with errors in PHP

Hello I need your help guys, I am using PHP and MYSQLI for my project. I have a form with which contains one text input field and three check boxes. When a user checks two boxes out of three and submits the form without filling the text input field I am showing an error.

Now what I want to achieve is that the particular check boxes that the user has checked should not get unchecked when error is displayed. Please understand that the category field will be same for all the check boxes in the form.

My form example is below:

<?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>

Answer

Do an in_array() check to see if the fruit is in the array, and then echo out checked="checked" to have it check the box (again).

<?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>
Comments