问题
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