使用codeigniter更新mysql数据库中的多个选择值

时间:2013-11-29 17:57:58

标签: php mysql codeigniter multiple-select

我的产品类别有多个选择,我有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);
}

1 个答案:

答案 0 :(得分:2)

首先删除类别,然后插入

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