Search code examples
phpcodeignitercrud

How To Insert and Update Data From Same Form using Codeigniter


Can Anyone Help me to write Controller,Model and View From Which There Would Be a Single form(View) That takes the Hidden Id and Controller Checks whether The Request From View have id or not and depending upon that it would insert and update the same.


Solution

  • Basically you just have to check if the hidden id exists in your database or not. If it doesn't then you insert, if it does you update. Generally this is how you do it:

    <?php
    
    class some_controller extends CI_Controller {
    
        /**
         * Submits the form
         * 
         * @return boolean
         */
        public function submit_form() {
            $id = $this->input->post('id');
            $data = array(
                'somedata' => $this->input->post('somedata'),
                'someotherdata' => $this->input->post('someotherdata')
            );
            $this->load->model('some_model');
            if (!is_null($id) && $this->some_model->id_exists($id)) {
                return $this->db->update('sometable', array('id' => $id), $data);
            } else {
                // assumes sometable autoincrements id
                // otherwise $data = array_merge(array('id' => $id), $data);
                return $this->db->insert('sometable', $data);
            }
        }
    
    }
    
    class some_model extends CI_Model {
    
        /**
         * Checks if id exists in sometable
         * 
         * @return boolean TRUE if item with $id exists in sometable
         */
        public function id_exists($id) {
            $this->db->where('id', $id);
            return $this->db->count_all_results('sometable') > 0;
        }
    
    }
    

    Please note: good practice would call for moving the insert and update (in fact all queries) into a model. This is just an example.