如何使用php和mysql插入选中的复选框并删除未选中的复选框?

I have a 3 tables: product, category and product_category. I am creating a form who edit(insert/delete) categories for a product. I am trying to insert an array of checkboxes in a relation table.

<input name="category[]" type="checkbox" value="<?php echo $cat->slug; ?>">

I know how to insert the checked values, but I don't know how to delete the unchecked ones.

$category = $_POST['category'];

for ($i = 0; $i < count($category); $i++) {
    if (!empty($category)) {
        $verifycategory = BD::conn()->prepare("SELECT * FROM `product_category` WHERE id_product = ? AND id_category = ?");
        $verifycategory->execute(array($id_prod, $category[$i]));
        if ($verifycategory->rowCount() == 0) {
            $anm = BD::conn()->prepare("INSERT INTO product_category(id_product, id_category) VALUES(?,?)");
            $anm->execute(array($id_prod, $category[$i]));
        }
    }
}
dongsuiwo0279
dongsuiwo0279 找到一个非常简单快速的解决方案!删除与产品相关的所有记录,然后重新插入。在我的例子中,关系表的id无关紧要。
一年多之前 回复
dos71253
dos71253 如果在插入刷新页面后没有涉及jquery/js,并且基于从产品类别中选择的显示复选框应该反映您的更改。实际上没有删除,它甚至不会在那里!..或者可以使用.html并使用jquery替换文本
一年多之前 回复
doubaolan2842
doubaolan2842 更好,使用??添加默认值null-coalescing运算符。
一年多之前 回复
dounouxi1020
dounouxi1020 使用stackoverflow.com/questions/19239536/...中描述的隐藏字段。
一年多之前 回复

1个回答

When you created the form/output you must have had an array of the possible checkboxes.

Just compare the values in this list to the ones posted.

$aCheckboxes = array(
    '0' => array('ID' => 1, 'Name' => 'box1'),
    '1' => array('ID' => 2, 'Name' => 'box2'),
    '2' => array('ID' => 3, 'Name' => 'box3')
);

$aToDelete = array();

foreach($aCheckboxes as $iPos => $a){
    if(!in_array($a['ID'], $_POST['category']){
        $aToDelete[] = (int)$_POST['category'];
    }
}

var_dump($aToDelete);
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问