dongzhuang5741 2019-04-29 20:57
浏览 82

如何使用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]));
        }
    }
}
  • 写回答

1条回答

  • douhuiyan2772 2019-04-29 21:59
    关注

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

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题