简体   繁体   中英

How to Insert checked checkboxes and delete unchecked checkboxes using php and 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]));
        }
    }
}

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM