使用codeigniter在mysql数据库中更新多个选择值 [英] update multiple select values in mysql database using codeigniter
本文介绍了使用codeigniter在mysql数据库中更新多个选择值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有多个选择我的产品类别,我有3个表为他们。我的表格如下:
I've got a multiple select for my product categories and I have 3 tables for them. My tables look like:
产品:
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
,它不更新。我想为我的产品设置一个类别,并删除两个其他,但当我看着我的数据库,我看到它改变了所有的行,如:
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
这是我的代码:
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);
}
推荐答案
先删除类别,然后插入
$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);
}
这篇关于使用codeigniter在mysql数据库中更新多个选择值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文