使用WHERE子句将复选框插入数据库

时间:2018-08-07 03:43:54

标签: php mysql

我正在尝试使用WHERE子句将复选框插入数据库。该代码重定向无任何错误。但是它没有更新到数据库中。当我取消选中该复选框时,该行将被删除,而ID则没有任何问题。这只是我遇到的INSERT问题。我似乎在这里找不到问题。

下面的代码无需使用WHERE子句即可工作。

$bId = $_POST['fm_id']; // this is coming from the hidden input field
if (isset($_POST['fm_day_hid'], $_POST['fm_day'])) {
    $ckb = $_POST['fm_day'];
    for ($i = 0; $i < count($ckb); $i++){
        if(!empty($ckb)){
            $arrayMovies = $ckb[$i];
            $sql = "INSERT INTO checkbox_batchdays (cbx_days) 
            SELECT * FROM (SELECT '$arrayMovies') AS tmp WHERE NOT EXISTS 
            (SELECT cbx_days FROM checkbox_batchdays WHERE cbx_days = '$arrayMovies') 
            WHERE cbx_batchid='$bId'";

            $query = mysqli_query($con, $sql);
        }
    }
    foreach($_POST['fm_day_hid'] as $moviesHidden) {
        if(!in_array($moviesHidden, $_POST['fm_day'])){
            $sql = "DELETE FROM checkbox_batchdays 
            WHERE cbx_days='$moviesHidden' AND cbx_batchid = '$bId'";

            $query = mysqli_query($con, $sql);
        }
    }
}
else {
    $sql = "DELETE FROM checkbox_batchdays WHERE cbx_batchid = '$bId'";
    $query = mysqli_query($con, $sql);
}

if( $query ) {
    header("Location: ../../batches.php");
}
else {
    echo "Not Deleted!";
}

1 个答案:

答案 0 :(得分:0)

这是答案。

for ($i = 0; $i < count($ckb); $i++){
    if(!empty($ckb)){
        $arrayMovies = $ckb[$i];
        $sql = "INSERT INTO checkbox_batchdays (cbx_batchid, cbx_days)
                    SELECT * FROM
                        (SELECT '$bId', '$arrayMovies') AS tmp
                    WHERE NOT EXISTS
                        (SELECT cbx_batchid, cbx_days FROM checkbox_batchdays 
                        WHERE cbx_days = '$arrayMovies' AND cbx_batchid='$bId')";
        $query = mysqli_query($con, $sql);
    }
}