【问题标题】:update multiple select values in mysql database using codeigniter使用codeigniter更新mysql数据库中的多个选择值
【发布时间】:2013-12-15 23:20:55
【问题描述】:

我的产品类别有多项选择,我有 3 个表格供他们选择。我的表格如下所示:

产品:

product_id   |   product_name
     1       |    my_package

类别:

category_id   |   category_name
     1        |     category 1
     2        |     category 2
     3        |     category 3

product_categories:

pc_id   |   product_id   |   category_id
  1     |         1      |        1
  2     |         1      |        2
  3     |         1      |        3

当我想更新product_categories 表时,它不会更新。我只想为我的产品设置一个类别并删除另外两个类别,但是当我查看我的数据库时,我发现它更改了所有行,例如:

product_categories:

pc_id   |    product_id   |   category_id
  1     |         1       |        2
  2     |         1       |        2
  3     |         1       |        2

这是我的代码:

foreach($selected_categories as $selected_category){
    $selected_category_options[] = $selected_category->category_Id;
}

echo form_multiselect('product_category_id[]', $category_options, set_value('product_category_id', $selected_category_options));

这是我模型中的代码:

foreach($_POST['product_category_id'] as $key => $product_category_id){

    $options = array(
        'category_Id' => $product_category_id
    );

    $this->db->where('product_id', $options['product_id']);  
    $this->db->update('product_categories', $options);
}

【问题讨论】:

    标签: php mysql codeigniter multiple-select


    【解决方案1】:

    先删除类别再插入

    $options = array(
        'category_Id' => $_POST['product_category_id'][0],
        'product_id'  =>  'product id here'/* first category will be inserted only*/
    );
    
    $this->db->query("DELETE FROM product_categories WHERE product_id=". $options['product_id']); /* this will delete all categories assigned to $options['product_id']*/
    
    $this->db->insert('product_categories', $options); /* will insert the first category from $_POST['product_category_id']*/
    

    如果你想要多更新,那么试试这个

    $this->db->query("DELETE FROM product_categories WHERE product_id='product id here'";
    foreach($_POST['product_category_id'] as $key => $product_category_id){
    
    
    $options = array(
        'category_Id' => $product_category_id,
        'product_id'  =>  'product id here' /* first category will be inserted only*/
    );    
        $this->db->insert('product_categories', $options);
    }
    

    【讨论】:

    • 这是正确的做法吗?!还是只是解决问题的技巧?!
    • @Afshin 这不是正确的方法,它的快速解决方案正确的方法是从 post 中获取 cat id,并与 db 中的 cat id 进行比较,然后从 db 中删除不在 $_POST 中的那些并添加与比较相比是新的
    • 我知道这篇文章已经过时了,很抱歉。但只是出于好奇,是否可以仅将新项目更新到数据库并删除未选择的项目。而不是首先删除所有内容并更新。我对复选框有同样的问题。但我能够用一个隐藏的字段来解决这个问题。
    猜你喜欢
    • 1970-01-01
    • 2018-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-21
    • 2018-04-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多