Codeigniter insert if not exist and update if not

 

First you need to check whether the user or data is exits or not. then you can perform the update and insert operation.
$this->db->where(‘user_id’,$id);
$q = $this->db->get(‘profile’);

if ( $q->num_rows() > 0 )
{
$this->db->where(‘user_id’,$id);
$this->db->update(‘profile’,$data);
} else {
$this->db->set(‘user_id’, $id);
$this->db->insert(‘profile’,$data);
}
 

There is one more way by using mysql query
$query = ‘INSERT INTO table_name (id, name) VALUES (?, ?)
ON DUPLICATE KEY UPDATE name=VALUES(name)’;
 

Explanation
Suppose this is the table.

+—-+———-+
| id | name |
+—-+———-+
| 1 | Urfusion |
| 2 | Christian|
+—-+———-+

now we are performing ON DUPLICATE KEY UPDATE

INSERT INTO table_name VALUES (3,’Example’) ON DUPLICATE KEY UPDATE name=’Example’;

result is

+—-+———-+
| id | name |
+—-+———-+
| 1 | Urfusion |
| 2 | Christian|
| 3 | Example |
+—-+———-+

Example has been inserted into the table because there is no entry with the key id is there now if we are trying to insert data on the position 1 or 2 then
INSERT INTO table_name VALUES (1,’Name_changed’) ON DUPLICATE KEY UPDATE name=’Name_changed’;
 

The result is

| id | name |
+—-+————-+
| 1 | Name_changed|
| 2 | Christian |
| 3 | Example |
+—-+————-+

 

You may also like...

%d bloggers like this: