Conditional Insert Or Update In Codeigniter
detecting whether a database record should be inserted or updated based on its existence within a db table
Just struggled through the following scenario and thought it might be useful info. If you every have a situation where you are looking to either insert a record into a database if the results of your query return no results, or update the record in the database if the results are true, you can use the following:
public function insert_or_update(){
$data = array( //the first two variables are my conditions, the second is the info I want to insert or update
'question' => $this->input->post('question'),
'tag' => $this->input->post('tag'),
'examples' => $this->input->post('examples')
);
$conditions = array('question' => $data['question'],'tag' => $data['tag'] ); //if a row matches both my post's question and tag...
$query = $this->db->get_where('extra_examples', $conditions); //get the results
if ($query->num_rows() > 0){ //if there are results (1 or more rows are returned from the db) then update whatever's there:
$this->db->where($conditions); //make sure to add this where clause again - the "where" from your $query no longer applies to your update
$this->db->update('extra_examples', $data);
} else {
$this->db->insert('extra_examples', $data);
}
}
The key is the second "where" clause, inside the
if($query->num_rows() > 0).
The "where" from your $query no longer applies to your update.