Search code examples
phpcheckboxisset

PHP remeber checked checkboxes


I am trying to have a filter using checkboxes. Problem is when I unselect some boxes and submit values, all boxes are selected again. I think the problem can be here

if (isset($_POST['option_meno']))

What can be the problem? And yes Im new here, so any ideas hot to make my code simpler would help me also.

Thank you.

<?php

// Make a MySQL Connection
$query_o_meno = "SELECT meno FROM uctovnictvo GROUP BY meno ORDER BY meno"; 

$result_meno = mysql_query($query_o_meno) or die(mysql_error());



?>
<form method="post">
<?php


if (isset($_POST['Filtrovat'])) { 

    // Print checked checkboxes
        echo "<strong>Meno:</strong>";
        echo "<br />";
    while($row = mysql_fetch_array($result_meno)){
        //I believe the problem is line below ----------------------------- 
        if (isset($_POST['option_meno'])) {
            echo "<input type='checkbox' name='option_meno[]' value='".$row['meno']."' checked />" . $row['meno'];
            echo "<br />";
            //}
        }
        else{
            echo "<input type='checkbox' name='option_meno[]' value='".$row['meno']."' / >" . $row['meno'];
            echo "<br />";
        }

    }
    }

else{
    $option_meno = array();
        echo "<strong>Meno:</strong>";
        echo "<br />";
    while($row = mysql_fetch_array($result_meno)){
        echo "<input type='checkbox' name='option_meno[]' value='".$row['meno']."' checked />" . $row['meno'];
        echo "<br />";
        $option_meno[] = $row['meno'];
        }   
    }


?>
<input type="submit" name="Filtrovat" value="Filtrovat" />
</form>

Solution

  • This is not tested, but should work:

    if (isset($_POST['Filtrovat'])) 
    { 
        // Print checked checkboxes
        echo "<strong>Meno:</strong>";
        echo "<br />";
    
        while($row = mysql_fetch_array($result_meno))
        {   
            $checked = "";
            if(isset($_POST['option_meno']))
            $checked = in_array($row['meno'],$_POST['option_meno'])?" 
                       checked = 'checked' ":"";
    
            echo "<input type='checkbox' name='option_meno[]' 
                  value='".$row['meno']."' $checked / >" . $row['meno'];
            echo "<br />";
        }
    }