Home >>Codeigniter Tutorial >codeigniter insert data database

codeigniter insert data database

CodeIgniter Insert Data into Database

In this tutorial, We will understand how to insert data into database using Controller model and view. We will use users table to insert, display, update and delete.

This is users table structure

Table Name : users
user_id int primary key auto_increment
name char(50)
email varchar(100)
mobile bigint

Connecting to a Database

In CodeIgniter, We can connect with database in 2 ways. 1.Automatic Connecting - Automatic Connection can be done using application/config/autoload.php

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

2. Manual Connecting - If u want database connection for some specific Controller then u can use Manual Connection. in manual Connection u will have to Create connection for every Controller So it would be better to use Automatic Connection.


Creating a Controller

Create a new file under the path Application/controllers/Hello.php Copy the below given code in your controllers.

class Hello extends CI_Controller 
	public function __construct()
	//call CodeIgniter's default Constructor
	//load database libray manually
	//load Model

	public function savedata()
		//load registration view form
		//Check submit button 
		//get form's data and store in local varable
//call saverecords method of Hello_Model and pass variables as parameter
		echo "Records Saved Successfully";

Creating a View

Create a new file under the path Application/views/registration.php Copy the below given code in your view.

<!DOCTYPE html>
<title>Registration form</title>

	<form method="post">
		<table width="600" border="1" cellspacing="5" cellpadding="5">
    <td width="230">Enter Your Name </td>
    <td width="329"><input type="text" name="name"/></td>
    <td>Enter Your Email </td>
    <td><input type="text" name="email"/></td>
    <td>Enter Your Mobile </td>
    <td><input type="text" name="mobile"/></td>
    <td colspan="2" align="center"><input type="submit" name="save" value="Save Data"/></td>




Creating a Model

Create a new file under the path Application/models/Hello_Model.php Copy the below given code in your model.

class Hello_Model extends CI_Model 
	function saverecords($name,$email,$mobile)
	$query="insert into users values('','$name','$email','$mobile')";

Calling/run Hello Controller’s savedata method

Open your web browser and Pass : http://localhost/CodeIgniter/index.php/Hello/savedata

Output : View Page
insert database in codeigniter
Output : Database

No Sidebar ads