CodeIgniter- active record insert if new or update on duplicate

前端 未结 8 775
醉酒成梦
醉酒成梦 2020-12-29 04:46

Is it possible to do an active record query in CodeIgniter that will update an existing record if one already exists or insert if it doesnt, for the given k

8条回答
  •  没有蜡笔的小新
    2020-12-29 05:24

    Here is a method that I hope can accomplish the same

       /**
        * Used to insert new row if a duplicate entry is encounter it performs an update
        * @param string $table table name as string
        * @param array $data associative array of data and columns
        * @return mixed 
        */
       private function updateOnExist($table, $data)
       {
            $columns    = array();
            $values     = array();
            $upd_values = array();
            foreach ($data as $key => $val) {
                $columns[]    = $this->db->escape_identifiers($key);
                $val = $this->db->escape($val);
                $values[]     = $val;
                $upd_values[] = $key.'='.$val;
            }
            $sql = "INSERT INTO ". $this->db->dbprefix($table) ."(".implode(",", $columns).")values(".implode(', ', $values).")ON DUPLICATE KEY UPDATE".implode(",", $upd_values);
            return $this->db->query($sql);
    }
    

提交回复
热议问题