CodeIgniter- active record insert if new or update on duplicate

前端 未结 8 615
醉酒成梦
醉酒成梦 2020-12-29 04:46

Is it possible to do an active record query in CodeIgniter that will update an existing record if one already exists or insert if it doesnt, for the given k

相关标签:
8条回答
  • 2020-12-29 05:46

    If you use Codeigniter 3.0 or higher, you might want to consider using "$this->db->replace()". According to the user guide:

    "This method executes a REPLACE statement, which is basically the SQL standard for (optional) DELETE + INSERT, using PRIMARY and UNIQUE keys as the determining factor. In our case, it will save you from the need to implement complex logics with different combinations of select(), update(), delete() and insert() calls."

    In other words,

    • If it doesn't exist, it inserts a new record.
    • If it does exist, it updates it according to its primary or unique key.

    Just use it straight out of the box like:

    $data = array(
            'title' => 'My title',
            'name'  => 'My Name',
            'date'  => 'My date'
    );
    
    $this->db->replace('table', $data);
    

    No batteries required!!!

    0 讨论(0)
  • 2020-12-29 05:47

    I'm using this approach:

    1. configure your table mytable with unique id and unique key for the column xyz, which you want to update

    2. try to insert an array $data, using INSERT IGNORE INTO do avoid duplicates

      $insert_query = $this->db->insert_string('bt_ical_list', $data);
      $insert_query = str_replace('INSERT INTO','INSERT IGNORE INTO',$insert_query);
      $this->db->query($insert_query); 
      

      this inserts a row, if value in column xyz doesn't exist

    3. use function insert_id() to return an id if row was inserted, update if no row was inserted.

      if(!$this->db->insert_id()){
          $query=$this->db    ->where('xyz', $data['xyz'])
                              ->update('my_table',$data);
      };  
      
    0 讨论(0)
提交回复
热议问题