How to uses insert or replace in codeigniter

你离开我真会死。 提交于 2020-02-29 06:50:40

问题


 public function save($data, $id)
    {
      $this->db->insert OR REPLACE($this->table, $data);
      return $this->db->insert_id();
    }

if the data does no exist will be insert else the data exist will be replace


回答1:


Try this

Check Unique data filed to check where record exist

public function save($data, $id)
{
    $query = $this->db->query("SELECT * FROM table_name WHERE id = '{$data['id']}' ");
    $result = $query->result_array();
    $count = count($result);

    if (empty($count)) {

        $this->db->insert('mytable', $data); 
    }
    elseif ($count == 1) {
        $this->db->where('id', $data['id']);
        $this->db->update('mytable', $data); 
    }
}



回答2:


If you are using CodeIgniter v3.0.x then all you need is $this->db->replace() as it compiles and executes a REPLACE statement. (MySQL documentation on REPLACE)

The trick is to include your table's key field ($id in your question) in the $data array. Then you only need to pass one param to save().

 public function save($data)
  {
    $this->db->replace($this->table, $data);
    return $this->db->insert_id();
  }

I confess that I am not sure that insert_id() will return anything after update() is called.




回答3:


Shorthand:

$db_action = !(empty)$this->db->get_where($this->table, array('id', $id)) ? $this->db->insert($this->table, $data) : $this->db->where('id', $id)->update($this->table, $data);


来源:https://stackoverflow.com/questions/34241942/how-to-uses-insert-or-replace-in-codeigniter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!