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

前端 未结 3 1325
挽巷
挽巷 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:41

    First Select all image_id from the table.

    $data = $this->db->select(`image_id`)->get($this->table_name)->result_array();
    

    List image_id into an array.

    $image_ids=array();
    
    foreach($data as $key => $value):
    
    $image_ids[$key]=$value[`image_id`];
    
    endforeach;
    
    $update = array(
       array('image_id' => 1, 'name' => 'Party Gustav'),
       array('image_id' => 2, 'name' => 'Peter'),
       array('image_id' => 3, 'name' => 'Lisa')
    )
    

    Check if the image_ids exist:

    $update_query= $this->db->where_in(`image_ids`,$image_ids)
                   ->get($this->table_name)->result();
    
    if($update_query->num_rows() > 0):
    
      $this->db->update_batch($update,$this->table_name);//update if ids exist
    else
       $this->db->insert_batch($update,$this->table_name);//insert if does not exist
    endif;
    

提交回复
热议问题