How would I use ON DUPLICATE KEY UPDATE in my CodeIgniter model?

前端 未结 8 1522
暖寄归人
暖寄归人 2020-11-30 07:27

I have a CodeIgniter/PHP Model and I want to insert some data into the database.

However, I have this set in my \'raw\' SQL query:

ON DUPLICATE KEY U         


        
相关标签:
8条回答
  • 2020-11-30 08:29

    Simply done -

        $updt_str = '';
        foreach ($insert_array as $k => $v) {
            $updt_str = $updt_str.' '.$k.' = '.$v.',';
        }
        $updt_str = substr_replace($updt_str,";", -1);
        $this->db->query($this->db->insert_string('table_name', $insert_array).' ON DUPLICATE KEY UPDATE '.$updt_str);
    
    0 讨论(0)
  • 2020-11-30 08:31

    You can add the "ON DUPLICATE" statement without modifying any core files.

    $sql = $this->db->insert_string('table', $data) . ' ON DUPLICATE KEY UPDATE duplicate=LAST_INSERT_ID(duplicate)';
    $this->db->query($sql);
    $id = $this->db->insert_id();
    

    I hope it's gonna help someone.

    0 讨论(0)
提交回复
热议问题