PDO多个复选框插入或删除

时间:2017-08-29 13:06:55

标签: php checkbox pdo

我需要帮助才能通过checkboxe链接三个表:

功能表(id,title,sulg)

帖子表(id,title,slug,added)

posts_features(fea_id,post_id)

<input type="text" name="title" value="$post->title">
<input type="text" name="slug" value="$post->slug">
// importing all features 
<input type="checkbox" name="featuresid[]" value="$features->id">

如果选中(插入) ,如果不存在。

foreach ($_POST['featuresid'] as $choice) {
$sql = $dbh->prepare("INSERT INTO posts_features (fea_id, post_id) VALUES ($choice, $id)");
$sql->execute();
}

如果从posts_features中取消选中(删除)

$sql = $dbh->prepare("delete form posts_features where ........

提前致谢。

2 个答案:

答案 0 :(得分:1)

如果未选中复选框,则$_POST不会被$_POST检查,因此您无法看到(从$_POST开始)哪些功能检查。

有几种方法可以做到这一点,但如果没有关于您的应用程序的更多信息,很难做出最好的&#34;建议,但这里的一个方法将利用$features->id

添加额外的&#34;隐藏&#34;输入,使用相应的<input type="checkbox" name="featuresid[]" value="$features->id"> <input type="hidden" name="existing[]" value="$features->id"> 来设置&#34;现有的&#34;输入:

注意:我在上面的代码中遵循您的约定来证明这一点,即使它们显然是伪代码,并且赢得了&n = t工作正常。

foreach ($_POST['featuresid'] as $choice) {
    $sql = $dbh->prepare("INSERT INTO posts_features (fea_id, post_id) VALUES ($choice, $id)");
    $sql->execute();
}

// loop through ALL feature ids listed on the page
foreach( $_POST['existing'] AS $features_id ) {
    // if the feature id wasn't in the checkboxes, then delete
    if ( ! in_array( $features_id, $_POST['featuresid'] ) ) {
        $sql = $dbh->prepare("DELETE FROM posts_features WHERE ........");
    }
}

然后,您可以像这样利用您的循环:

.header{
}

答案 1 :(得分:0)

未经检查的复选框不会发送给PHP。因此,当您遍历$_POST['featuresid']时,您将只看到已选中的复选框。这意味着删除未经检查的功能实际上意味着删除不在已检查组中的所有功能。

首先,插入所选功能:重要不要在循环中执行数据库查询;他们真的会减慢你的脚本速度。相反,insert all records at once。您还应该使用参数化查询;永远不要将用户提供的值直接插入数据库查询中!

插入后,删除那些未选中的功能:

DELETE FROM posts_features WHERE fea_id NOT IN (?, ?, ?, ?)

?中的每一个都对应$_POST['featuresid']

中的值

另一种方法是,如果您希望PHP为每个功能接收明确的选定/未选定值,则对HTML中的每个功能使用是/否单选按钮或下拉列表。