从数据库查询构建复选框列表,并在表单提交后保留该复选框


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

我试图建立一个简单的表单,查询数据库,抓取电子邮件地址列表,然后根据结果创建一个表。我想要做的是保留提交后的复选框,但我有麻烦弄清楚它基于我已经创建了我的表的方式。如果我手动构建表,我可以做到这一点,但这违背了目的。这是我正在使用的代码,再次,我想要做的唯一改变是保留复选框。

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

请帮忙,谢谢

只需检查循环中的当前邮件是否存在于$_POST['select']中,如果存在则进行检查,如果不存在则清除检查。此复选框将在输入复选框中显示为<?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
     }
 ?>

检查$row['Email']是否为空,则输出"checked"属性

<?php
while($row = $result->fetch_assoc()) {
unset($email);
$email = $row['Email'];
?>
<tr><td><input type="checkbox" name="select[]" value="<?php echo $email;?>"<?php if($row['Email'] != false) { echo ' checked'; } ?>><?php echo $email; ?></td></tr>
<?php
}
?>