Insert Data
Query Builder Class

Codeigniter provide us pattern that we can retrieve data, insert data, updata data and fetch data with minimal scripting, this is also call Active record.

This is safer(From SQL Injection), escaped automatically and easy to change any database(Oracle,PostgreSQL etc)

$data = array(
'name' => 'Honey',
'email' => 'honeyphpdeveloper@gmail.com'
);

$this->db->insert('info', $data);

How to Insert Data into Database.

Step to Insert data into database

1- Create Table in Database(phpmyadmin)
2- Create HTML page - Create HTML page to accept user input
3- Create Controller - To Run Script
4- Create Model - Create Model for write insert query

Create HTML page and save in view folder (view->inputdata.php)

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<html>
<head>
<title>Insert Data</title>
</head>
<body>
<form name="frm" action="<?php echo base_url(); ?>index.php/user/insert" method="post">
Enter Name<input name="name"  type="text"  value=""/><br />
Enter Email<input name="email"  type="text" value=""/><br />
Enter City<input name="city"  type="text"  value=""/><br />
<input name="btn"  type="submit"  value="Submit"/>
</form>
</body>
</html>

Create Controller and save in controller folder(controllers->user.php)

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

class User extends CI_Controller {

public  function __construct() {
parent::__construct();
$this->load->database();
$this->load->helper('url');
$this->load->model('user_model');
}

public  function index()
{
$this->load->view('inputdata');
}

public function insert()
{
$this->user_model->user_insert();
$this->load->view('inputdata');
}

}

Create Model for Insert data and save in application->models->User_Model.php

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

class User_Model extends CI_Model {

public  function user_insert()
{

$data = array(
'name'  =>  $this->input->post('name'),
'email'  =>  $this->input->post('email'),
'city'  =>  $this->input->post('city')
);

$this->db->insert('tbl_user', $data);
}

}


Previous
Next