Ed Dunn Ed Dunn - 5 months ago 13
PHP Question

Building a checkbox list from a database query and retaining the checkbox after a form submit

I am trying to build a simple form which queries a database, grabs a list of email addresses and then creates a table based on the results. What I would like it to do is retain the checked boxes after a submission but am having trouble figuring it out based on the way I've created my table. I can do it no problem if I manually build the table but that defeats the purpose. Here is the code I am working with, again the only change I would like it to do is retain the checked boxes.

<html>
<head>
<title>Test</title>
<link rel="stylesheet" type="text/css" href="style/style.css"/>
</head>
<body>
<?php include('include/connect.php'); ?>
<h1>This is a test</h1>
<div class="emailform">
<form action="" method="post">
<table id="emails">
<?php
while($row = $result->fetch_assoc()) {
unset($email);
$email = $row['Email'];
?>
<tr><td><input type="checkbox" name="select[]" value="<?php echo $email;?>"/><?php echo $email; ?></td></tr>
<?php
}
?>
</table>
<br/><br/>
<input id="manual" type="text" name="select[]"><br/><br/><br/>
<button type="submit" name="SubmitButton">Select Email Addresses</button>
</form>
</div>
<?php
if(isset($_POST['SubmitButton'])){
if(isset($_POST['select'])){
$shift = $_POST['select'];
if (count($shift) > 1 ){
$list = implode(", ", $shift);
echo $list;
} else {
echo "$shift[0] <br/>";
}
}
}
?>
</body>
</html>


Help would be appreciated, thanks

Answer

Just check if the current email in the loop exists in $_POST['select'], if it is, you check it, if it is not, clear the check. This check will be displayed in the input checkbox as <?php echo $checked;?> :

 <?php
     while($row = $result->fetch_assoc()) {
         unset($email);
         $email = $row['Email'];
         // IF EMAIL EXISTS IN $_POST, CHECK IT.
           $checked = "";
           if(isset($_POST['select'])){
                $shift = $_POST['select'];
                $list = implode(", ", $shift);
                if (strpos($list,$email)===false)
                     $checked = "";         // EMAIL NOT IN $_POST.
                else $checked = "checked";  // EMAIL IS IN $_POST.
           }
 ?>
 <tr><td><input type="checkbox" name="select[]" <?php echo $checked;?>
          value="<?php echo $email;?>"/><?php echo $email; ?></td></tr>
 <?php
     }
 ?>