Update a row, but insert if row doesn't exist in codeigniter

前端 未结 3 1354
挽巷
挽巷 2021-01-23 11:29

I want to do an insert of row in a table, like this:

$this->db->update_batch($this->table_name, $update, \'image_id\');

if ($this->db->affected_r         


        
3条回答
  •  庸人自扰
    2021-01-23 11:57

    I think what you're looking for is INSERT IGNORE INTO. Unfortunately, Codeigniter doesn't have an equivalent Active Record function. A discussion on the Codeigniter forums and this similar SO question suggest a method like this:

    foreach ($update as $update_item) {
        $insert_query = $this->db->insert_string($this->table_name, $update_data['name']);
        $insert_query = str_replace('INSERT INTO','INSERT IGNORE INTO',$insert_query);
        $this->db->query($insert_query);  
    }
    

    Also note that the image_id must be UNIQUE.

提交回复
热议问题