0

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]));
        }
    }
}
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
K. Nathan
  • 17
  • 10
  • Use hidden fields like described at https://stackoverflow.com/questions/19239536/how-get-value-for-unchecked-checkbox-in-checkbox-elements-when-form-posted – cjs1978 Apr 29 '19 at 21:00
  • Better, add default values using `??` null-coalescing operator. – Dharman Apr 29 '19 at 21:03
  • if no jquery/js involved after insert refresh page and display checkbox based on the select from product category should reflect your change . Not actually delete , it wont even be there !! ..or may use .html and replace text using jquery – zod Apr 29 '19 at 21:04
  • Found a very easy and fast solution! Delete all records related to the product and Insert again. In my case, the id of the relation table don't matter. – K. Nathan Apr 30 '19 at 14:24

1 Answers1

0

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);
atoms
  • 2,993
  • 2
  • 22
  • 43