Skip to content
Advertisement

trying to update on duplicate key but its not working

I have this line of sql:

$field=array(
 'image'=>$datosArr[0],
 'field'=>$datosArr[1],
 'user_id'=>session()->get("id"),
);      
    
$query = $this->db->table($datosArr[1])->insert($field).' ON DUPLICATE KEY UPDATE image="'.$datosArr[0].'",field="'.$datosArr[1].'"';

It works perfectlly when I only need to insert, but it is failing when trying to update,it has an user_id that is primary key, so I hope thats what gets on the key, the other array variables $datosArr are strings, any ideas?

Basically im trying to update when user_id exists , I want to update field and image when user_id already exists.

Database contains user_id (Primary Key), field and image which both are varchar, thanks

Advertisement

Answer

I found the solution here, it works for Codeigniter 4, I dont know the lowest version that can do it, but it works fine. CodeIgniter- active record insert if new or update on duplicate

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement