如何在点火器中使用插入或更换


How to uses insert or replace in codeigniter

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

如果数据不存在,则插入,否则数据存在将被替换

试试这个

选中唯一数据归档以检查记录存在的位置

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); 
    }
}

如果您使用的是 CodeIgniter v3.0.x,那么您只需要 $this->db->replace(( 编译并执行 REPLACE 语句。(关于替换的MySQL文档(

诀窍是在$data数组中包含表的键字段($id在您的问题中(。然后你只需要传递一个参数来save() .

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

承认,我不确定insert_id()在调用update()后会返回任何内容。

速记:

$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);