无法将复选框值发送到MySQL数据库?

时间:2017-11-24 22:35:20

标签: php mysql checkbox

我正在尝试根据表单中的复选框(Watched)在我的数据库中存储一个布尔值。如果未在表单提交中选中该复选框,则应发送0;否则为1。

但是,无论是否检查,它都会发送值0。 Title Field和Genre字段发送完美,但Watched条件无法正常工作。我很难过,很难想到这有什么想法吗?

<?php 

    require 'config/config.php';
    require 'config/db.php';

    // Check for Submit
    if(isset($_POST['submit'])) {
        // Get Form Data
        $title = mysqli_real_escape_string($conn, $_POST['title']);
        $genre = mysqli_real_escape_string($conn, $_POST['genre']);
        if (isset($_POST['watched']) && ($_POST['watched'] == "value")) {
            $watched = 1;
        } else {
            $watched = 0;
        }

        $query = "INSERT INTO movies(name, genre, watched) VALUES('$title', '$genre', '$watched')";

        if (mysqli_query($conn, $query)) {
            header('Location: '.ROOT_URL.'');
        } else {
            echo "ERROR: " . mysqli_error($conn);
        }
    }

?>

                <form method="POST" action="<?php $_SERVER['PHP_SELF']; ?>">

                    <div class="md-form">
                        <input type="text" id="form1" class="form-control" name="title">
                        <label for="form1" class="">Title</label>
                    </div>

                    <div class="md-form">
                        <input type="text" id="form1" class="form-control" name="genre">
                        <label for="form1" class="">Genre</label>
                    </div>

                    <div class="form-group">
                        <input type="checkbox" id="checkbox1" name="watched">
                        <label for="checkbox1">Have you watched it already?</label>
                    </div>

                    <input type="submit" name="submit" value="submit" class="btn btn-primary">

                </form>

1 个答案:

答案 0 :(得分:0)

您永远不会为表单HTML中的复选框设置实际值,因此复选框的值将永远不存在,这意味着您的if语句将始终返回false。

只需改变一下:

<input type="checkbox" id="checkbox1" name="watched">

到此:

<input type="checkbox" id="checkbox1" name="watched" value="value">