Inserting data into a table in database with codeigniter

This is an important part in the codeigniter because i nthis section we are creating a model for inserting data to our database. Codeigniter has a feature to insert data to a database table with one line by creating all the data to be inserted into an array and store them by passing it with a simple variable to the database.

$this->Users_model->insert_user($u_data);

In the above code that we added in the register_process() function in the controller inserts the data to a particular table in our database.


  • Users_model : this is the new model we created with a .php extension.
  • insert_user()  : this is the function inside that model.
  • u_data            : this is the variable in which the data is stored.
The following is the new edited code in the controller :

   public function register_process()
   {
     if($this->input->post('u_reg'))
     {
      $u_email=$this->input->post('u_email');
       $u_name=$this->input->post('u_name');
       $u_pass=md5($this->input->post('u_password'));

       $u_data=array('u_email'=>$u_email,'u_name'=>$u_name,'u_pass'=>$u_pass);
       $this->Users_model->insert_user($u_data);
       redirect('login','refresh');
     }
     else
     {
       redirect('register','refresh');
     }
   }


User_model.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Users_model extends CI_Model {

  public function insert_user($user_data)
  {
  $this->db->insert('users',$user_data);
  }
  
}


  • users : table name.


We also need to load the model at the top of the controller as below :

  public function __construct()
  {
    parent::__construct();
    $this->load->model('Users_model');
  }




Prev
Next

Comments

Popular posts from this blog

Node.js Cheat Sheet

Codeigniter ! Simple But Powerful

Bootstrap ? What is it ?