foreach复选框以保持POST值

时间:2017-01-22 12:39:46

标签: php foreach

我试图将POST值存储到选定的复选框中,我在提交表单后存储数据时遇到了一些问题。这就是我所拥有的:

<fieldset>
            <legend>Categories:</legend>
            <?php $sql3 = 'SELECT id, name FROM category'; 
                    foreach ($dbConnection->query($sql3) as $category) { ?>
            <div>       
                <label for="category<?php echo($category['id']);?>">
                <input type="checkbox" name="categories[]" id="category<?php echo($category['id']); ?>" value="<?php echo($category['id']); ?>"
                <?php if(isset($_POST['category']) && $_POST['category'] == $category['id']) { echo 'checked'; } ?>>
                <?php echo($category['name']); ?></label>
            </div>
            <?php } ?>
            </fieldset>

有人可以借助它吗?

1 个答案:

答案 0 :(得分:1)

将你的if语句更改为:

<?php if(isset($_POST['categories']) && in_array($category['id'],$_POST['categories'])) { echo 'checked'; } ?>>
        <?php echo($category['name']); ?></label>