php Codeigniter 如果不存在则插入,如果不存在则更新

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35223752/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:23:11  来源:igfitidea点击:

Codeigniter insert if not exist and update if not

phpdatabasecodeigniter

提问by Christian

i have two tables for these product category the one where i store the product categories and the other one is the product list where i insert products when you insert a new product there will be a dropdown to choose from categories stored on the product category but if you want to add another category there is an "other" option in the dropdown and a textarea will apear and lets you create another category my problem is if I add a new product with an existing category in the database it doesnt insert into the two tables but if I add a new product with a new category it successfuly inserts my controller:

我有这些产品类别的两个表格,一个是我存储产品类别的表格,另一个是我在插入新产品时插入产品的产品列表,将有一个下拉列表可以从产品类别中存储的类别中进行选择,但如果您想添加另一个类别,下拉列表中有一个“其他”选项,文本区域将出现并让您创建另一个类别我的问题是,如果我在数据库中添加一个具有现有类别的新产品,它不会插入到两个表中但是如果我添加一个新产品的新类别,它会成功插入我的控制器:

 function do_upload() {


    $config['upload_path'] = './assets/';
    $config['allowed_types'] = 'gif|jpg|png';
    $config['max_size'] = '2000';
    $config['max_width'] = '2000';
    $config['max_height'] = '2000';
    $config['new_image'] = './assets/';

    $config['overwrite'] = TRUE;
    $this->load->library('upload', $config);
    $this->form_validation->set_rules('name', 'Product Name', 'required|xss_clean');
    $this->form_validation->set_rules('description', 'Product Description', 'required|xss_clean');
    $this->form_validation->set_rules('price', 'Price', 'required');
    if (!$this->upload->do_upload() || !$this->form_validation->run()) {
        $error = array('error' => $this->upload->display_errors());
        redirect('add_products');
    } else {

        $data = $this->upload->data();
        $this->thumb($data);

         $category = $_POST["prod_category"];
        if($category  == "2")
            {
            $category = $_POST["other_category"];

            }
        $file = array(
            'img_name' => $data['raw_name'],
            'thumb_name' => $data['raw_name'] . '_thumb',
            'ext' => $data['file_ext'],
            'product_name' => $this->input->post('name'),
            'product_description' => $this->input->post('description'),
            'product_price' => $this->input->post('price'),
            'product_category' =>$category,    


        );

         $this->db->insert("product_category",array("category"=>$category));
          $this->User->insert_prod($file);
        $data = array('upload_data' => $this->upload->data());
        echo '<script>alert("You Have Successfully Added a new Product!");</script>';
        redirect('admin_products','refresh');
    }
}

model

模型

public function insert_prod($file){
        $this->db->insert('product_table',$file);
    }

回答by urfusion

First you need to check whether the user or data is exits or not. then you can perform the update and insert operation.

首先您需要检查用户或数据是否存在。然后您可以执行更新和插入操作。

   $this->db->where('user_id',$id);
   $q = $this->db->get('profile');

   if ( $q->num_rows() > 0 ) 
   {
      $this->db->where('user_id',$id);
      $this->db->update('profile',$data);
   } else {
      $this->db->set('user_id', $id);
      $this->db->insert('profile',$data);
   }

There is one more way by using mysql query

还有一种方法是使用 mysql 查询

   $query = 'INSERT INTO table_name (id, name) VALUES (?, ?)
     ON DUPLICATE KEY UPDATE name=VALUES(name)';

ExplanationSuppose this is the table.

说明假设这是表。

+----+----------+
| id | name     |
+----+----------+
|  1 | Urfusion |
|  2 | Christian|
+----+----------+

now we are performing ON DUPLICATE KEY UPDATE

现在我们正在表演 ON DUPLICATE KEY UPDATE

INSERT INTO table_name VALUES (3,'Example') ON DUPLICATE KEY UPDATE name='Example';

result is

结果是

+----+----------+
| id | name     |
+----+----------+
|  1 | Urfusion |
|  2 | Christian|
|  3 | Example  |
+----+----------+

Examplehas been inserted into the table because there is no entry with the key idis there now if we are trying to insert data on the position 1 or 2 then

Example已插入到表中,因为没有带键的条目,id如果我们尝试在位置 1 或 2 上插入数据,那么现在存在

INSERT INTO table_name VALUES (1,'Name_changed') ON DUPLICATE KEY UPDATE name='Name_changed';

Then result is

那么结果是

| id | name        |
+----+-------------+
|  1 | Name_changed|
|  2 | Christian   |
|  3 | Example     |
+----+-------------+

For more information

欲了解更多信息

回答by ??? ?????? ????????

$this->db->replace('profile',$data);

if exists update, else insert

如果存在更新,否则插入