Adding new record in codeigniter

Here is an example of how to add a new record in CodeIgniter:

Step 1: Create a model

Create a new file in the models directory of your CodeIgniter application, e.g. User_model.php. In this file, define a method to add a new record:

<?php

class User_model extends CI_Model {

    public function add_user($data) {
        $this->db->insert('users', $data);
        return $this->db->insert_id();
    }

}

In this example, the add_user method takes an array of data as an argument, and uses the db object to insert the data into the users table. The insert_id method returns the ID of the newly inserted record.

Step 2: Create a controller

Create a new file in the controllers directory of your CodeIgniter application, e.g. User_controller.php. In this file, define a method to add a new record:

<?php

class User_controller extends CI_Controller {

    public function add_user() {
        $this->load->model('User_model');
        $data = array(
            'name' => $this->input->post('name'),
            'email' => $this->input->post('email'),
            // Add more fields as needed
        );
        $user_id = $this->User_model->add_user($data);
        if ($user_id) {
            $this->session->set_flashdata('message', 'User added successfully!');
            redirect('user/list');
        } else {
            $this->session->set_flashdata('error', 'Error adding user!');
            redirect('user/add');
        }
    }

}

In this example, the add_user method loads the User_model model, and uses the input class to retrieve the posted data. It then calls the add_user method of the model to add the new record. If the record is added successfully, it sets a flash message and redirects to the list method of the same controller. If there is an error, it sets an error message and redirects back to the add method.

Step 3: Create a view

Create a new file in the views directory of your CodeIgniter application, e.g. add_user.php. In this file, create a form to add a new user:

<?php

echo form_open('user/add');

echo form_label('Name:', 'name');
echo form_input('name', '', 'id="name"');

echo form_label('Email:', 'email');
echo form_input('email', '', 'id="email"');

echo form_submit('submit', 'Add User');

echo form_close();

?>

In this example, the form uses the form_open helper to generate the form opening tag, and the form_label and form_input helpers to generate the form fields. The form_submit helper generates the submit button.

Step 4: Add a route

In the routes.php file of your CodeIgniter application, add a route to map the add_user method of the User_controller to the add URI:

$route['user/add'] = 'user/add_user';

That's it! Now you can access the add method of the User_controller by visiting http://example.com/user/add in your browser. Fill out the form and submit it to add a new user.