Insert record to Database Table – Codeigniter

All logical operation and database handling done in the Models like insert, update or fetch records.

Codeigniter has predefined Database methods to perform database request.

In the demonstration, with View show the HTML form and when the user submits the forms then call the Model method to insert record from the controller.

Insert record to Database Table - Codeigniter


Contents

  1. Table structure
  2. Configuration
  3. Model
  4. Controller
  5. View
  6. Conclusion

 

1. Table structure

I am using users table.

CREATE TABLE `users` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `username` varchar(80) NOT NULL,
  `name` varchar(80) NOT NULL,
  `email` varchar(80) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

 

2. Configuration

Navigate to application/config/database.php and define Database connection.

$db['default'] = array(
 'dsn' => '',
 'hostname' => 'localhost',
 'username' => 'root', // Username
 'password' => '', // Password
 'database' => 'tutorial', // Database name
 'dbdriver' => 'mysqli',
 'dbprefix' => '',
 'pconnect' => FALSE,
 'db_debug' => (ENVIRONMENT !== 'production'),
 'cache_on' => FALSE,
 'cachedir' => '',
 'char_set' => 'utf8',
 'dbcollat' => 'utf8_general_ci',
 'swap_pre' => '',
 'encrypt' => FALSE,
 'compress' => FALSE,
 'stricton' => FALSE,
 'failover' => array(),
 'save_queries' => TRUE
);

Default controller

Open application/config/routes.php and edit default_controller value to User.

$route['default_controller'] = 'User';

Load Database

To access the MySQL database require loading database library.

Open application/config/autoload.php and add the database in libraries array().

$autoload['libraries'] = array("database");

 

3. Model

Navigate to application/models/ directory and create new Main_model.php file.

Creating a Class Main_model and extends CI_Model Class. Within this class define a method insertNewuser() which inserts records into the MySQL Database table.

Calling this method from the controller when the user submits the form.

Check username is already in use or not if not then insert record with $this->db->insert('users', $newuser).

Here,

  • The first parameter is the name of the table and
  • The second parameter is an associative array which contains field name and value.

Completed Code

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

class Main_model extends CI_Model {

 function insertNewuser($postData){
 
  $response = "";
 
  if($postData['txt_name'] !='' || $postData['txt_uname'] !='' || $postData['txt_email'] !='' ){
 
   // Check entry
   $this->db->select('count(*) as allcount');
   $this->db->where('username', $postData['txt_uname']);
   $q = $this->db->get('users');
   $result = $q->result_array();
 
   if($result[0]['allcount'] == 0){

    // Insert record
    $newuser = array(
      "name" => trim($postData['txt_name']),
      "username" => trim($postData['txt_uname']),
      "email" => trim($postData['txt_email'])
    );

    // $this->db->insert( [table-name], Array )
    $this->db->insert('users', $newuser);

    $response = "Record insert successfully.";

   }else{
    $response = "Username already in use";
   }
  }else{
   $response = "Form is empty.";
  }
 
  return $response;
 }

}

 

4. Controller

Navigate to application/controllers/ directory and create a User.php file.

Create a new Class User and extends CI_controller Class.

Define an index() method from where load model and view. Handle request when the <form> is got submitted.

Read POST value with $this->input->post(); and pass it to model insertNewuser() method. According to response pass the data to the view.

Completed Code

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

class User extends CI_Controller {

 public function index(){

  // load base_url
  $this->load->helper('url');

  // Check form submit or not
  if($this->input->post('submit') != NULL ){
 
   // POST data
   $postData = $this->input->post();

   //load model
   $this->load->model('Main_model');

   // get data
   $data['response'] = $this->Main_model->insertNewuser($postData);
 
   // load view
   $this->load->view('user_view',$data);
  }else{
   $data['response'] = '';

   // load view
   $this->load->view('user_view');
  }
 
 }

}

 

5. View

Navigate to application/views/ directory and create a user_view.php file.

Create an HTML form and set form action attribute with base_url()

Completed Code

<!doctype html>
<html>
 <head>
  <title>Insert record to Database Table in Codeigniter</title>
 </head>
 <body>
  <b><?php if(isset($response)) echo $response; ?></b>
  <form method='post' action='<?php echo base_url(); ?>'>

   <table>
    <tr>
     <td>Name</td>
     <td><input type='text' name='txt_name'></td>
    </tr>
    <tr>
     <td>Username</td>
     <td><input type='text' name='txt_uname'></td>
    </tr>
    <tr>
     <td>Email</td>
     <td><input type='text' name='txt_email'></td>
    </tr>
    <tr>
     <td>&nbsp;</td>
     <td><input type='submit' name='submit' value='Submit'></td>
    </tr>
   </table>
 
  </form>
 </body>
</html>

6. Conclusion

By default, database library is not loaded you need to define in application/config/autoload.php.

If you want to learn the basis of Codeigniter then check my previous tutorial.

Related Post

Spread the love

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *