update multiple select values in mysql database using codeigniter

ε祈祈猫儿з 提交于 2019-12-08 13:16:45

问题


I've got a multiple select for my product categories and I have 3 tables for them. My tables look like:

products:

product_id   |   product_name
     1       |    my_package

categories:

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

When I want to update product_categories table, it doesn't update. I wanted to set just one category for my product and remove two others, but when I looked at my database I saw that it changed all the rows like:

product_categories:

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

This is my code in view:

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

and this is the code in my Model:

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

回答1:


First delete the categories and then insert

$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']*/

If you want a multi update then try this

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


来源:https://stackoverflow.com/questions/20291225/update-multiple-select-values-in-mysql-database-using-codeigniter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!