验证是否已选中复选框

时间:2017-01-22 15:05:54

标签: php post checkbox

如果未选中复选框,我试图显示错误消息。我设法完成输入字段,但不确定如何使用复选框完成它。这就是我到目前为止所做的:

    <?php
    # check if data has been posted
    if (!empty($_POST)) {
        # keep track validation errors
        $author_error = null;
        $categories_error = null;

        # keep track of post values
        $author = $_POST['author'];
        $categories = $_POST['categories'];

        # validate input
        if (empty($author)) {
            $author_error = 'Please select author';
            $valid = false;
        }

        if (empty($categories)) {
            $categories = 'Please select categories';
            $valid = false;
        }

        # if data is valid, insert into the database
        if ($valid) {

        }
    }
    ?>

        <div class="control-group <?php if (!empty($author_error)){ echo 'error'; } ?>">
            <label class="control-label">Author</label>
            <div class="controls">
                <select name="author" id="author">
                    <option value="">Select one</option>
                    <?php $sql2 = 'SELECT id, name FROM author'; 
                    foreach ($dbConnection->query($sql2) as $data2) { ?>
                    <option value="<?php echo $data2['id']; ?>" 
                        <?php if(isset($author) && $author == $data2['id']) { echo 'selected'; } ?>>
                        <?php echo $data2['name']; ?>
                    </option>
                    <?php } ?>
                </select>
                <?php if (!empty($author_error)) { echo '<span class="help-inline">' . $author_error . '</span>'; } ?>
            </div>
        </div>

        <div class="control-group <?php if (!empty($categories_error)){ echo 'error'; } ?>">
            <fieldset>
            <legend class="control-label">Categories:</legend>
            <?php $sql3 = 'SELECT id, name FROM category'; 
            foreach ($dbConnection->query($sql3) as $data3) { ?>
            <div class="controls">      
                <label for="category<?php echo($data3['id']);?>">
                    <input type="checkbox" name="categories" id="categories" value="<?php echo($data3['id']); ?>"
                    <?php if(isset($_POST['categories']) && in_array($data3['id'], $_POST['categories'])) { echo 'checked'; } ?>>
                    <?php echo($data3['name']); ?>
                </label>
            </div>
            <?php } ?>
            </fieldset>
            <?php if (!empty($categories_error)) { echo '<span class="help-inline controls">' . $categories_error . '</span>'; } ?>
        </div>

我在哪里出错了类别字段?

2 个答案:

答案 0 :(得分:3)

检查如下:

isset($_POST['categories'])

答案 1 :(得分:1)

在第62行,您正在检查$categories_error是否为空但您使用变量$categories在第19行存储错误消息