After creating form in CodeIgniter framework one must learn to insert data into a database. Following stepsĀ explains you, how this operationĀ can be done in easy way:-
- First, you mustĀ create a PHPĀ page inĀ View directoryĀ of CodeIgniter, in which a form is created using CodeIgniter’sĀ syntax.
- Second, you have to create class inĀ Controller directory, in which the above PHPĀ page(view) is loaded, applying validation over form fields and respectiveĀ model is loaded.
- Third, forĀ database connectivity in your application, a class is created inĀ Model directoryĀ with database insert function.Ā
You can also refer our live demo or download the Script file. Extract the downloaded files, save it in your local server and run it usingĀ pathĀ :
http://localhost/CodeIgniter-insert
-: See Also :-
Update Data in Database using CodeIgniter
Note :Ā You can also refer the Ā PHPProjectInstall.pdf Ā file given in the download code folder.
VIEW FILE:Ā insert_view.php
copy the below code in your view.
<html>
<head>
<title>Insert Data Into Database Using CodeIgniter Form</title>
<link href='http://fonts.googleapis.com/css?family=Marcellus' rel='stylesheet' type='text/css'/>
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>css/style.css" />
</head>
<body>
<div id="container">
<?php echo form_open('insert_ctrl'); ?>
<h1>Insert Data Into Database Using CodeIgniter</h1><hr/>
<?php if (isset($message)) { ?>
<CENTER><h3 style="color:green;">Data inserted successfully</h3></CENTER><br>
<?php } ?>
<?php echo form_label('Student Name :'); ?> <?php echo form_error('dname'); ?><br />
<?php echo form_input(array('id' => 'dname', 'name' => 'dname')); ?><br />
<?php echo form_label('Student Email :'); ?> <?php echo form_error('demail'); ?><br />
<?php echo form_input(array('id' => 'demail', 'name' => 'demail')); ?><br />
<?php echo form_label('Student Mobile No. :'); ?> <?php echo form_error('dmobile'); ?><br />
<?php echo form_input(array('id' => 'dmobile', 'name' => 'dmobile', 'placeholder' => '10 Digit Mobile No.')); ?><br />
<?php echo form_label('Student Address :'); ?> <?php echo form_error('daddress'); ?><br />
<?php echo form_input(array('id' => 'daddress', 'name' => 'daddress')); ?><br />
<?php echo form_submit(array('id' => 'submit', 'value' => 'Submit')); ?>
<?php echo form_close(); ?><br/>
<div id="fugo">
</div>
</div>
</body>
</html>
CONTROLLER FILE: insert_ctrl.php
copy the below code in your controller.
<?php
class insert_ctrl extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->model('insert_model');
}
function index() {
//Including validation library
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
//Validating Name Field
$this->form_validation->set_rules('dname', 'Username', 'required|min_length[5]|max_length[15]');
//Validating Email Field
$this->form_validation->set_rules('demail', 'Email', 'required|valid_email');
//Validating Mobile no. Field
$this->form_validation->set_rules('dmobile', 'Mobile No.', 'required|regex_match[/^[0-9]{10}$/]');
//Validating Address Field
$this->form_validation->set_rules('daddress', 'Address', 'required|min_length[10]|max_length[50]');
if ($this->form_validation->run() == FALSE) {
$this->load->view('insert_view');
} else {
//Setting values for tabel columns
$data = array(
'Student_Name' => $this->input->post('dname'),
'Student_Email' => $this->input->post('demail'),
'Student_Mobile' => $this->input->post('dmobile'),
'Student_Address' => $this->input->post('daddress')
);
//Transfering data to Model
$this->insert_model->form_insert($data);
$data['message'] = 'Data Inserted Successfully';
//Loading View
$this->load->view('insert_view', $data);
}
}
}
?>
MODELĀ FILE:Ā insert_model.php
Create new class in your model as shown below.
<?php
class insert_model extends CI_Model{
function __construct() {
parent::__construct();
}
function form_insert($data){
// Inserting in Table(students) of Database(college)
$this->db->insert('students', $data);
}
}
?>
My SQL Code Segment:
To create database and table, execute following codes in your My SQL .
CREATE DATABASE college;
CREATE TABLE students(
Student_id int(10) NOT NULL AUTO_INCREMENT,
Student_Name varchar(255) NOT NULL,
Student_Email varchar(255) NOT NULL,
Student_Mobile varchar(255) NOT NULL,
Student_Address varchar(255) NOT NULL,
PRIMARY KEY (Student_id)
)
Note :Ā .sql file included in project downloaded root folder you can also import them in mysql database.
CSS FILE: styles.css
Styling HTML Elements.
#container {
width:960px;
height:610px;
margin:50px auto
}
.error {
color:red;
font-size:13px;
margin-bottom:-15px
}
form {
width:345px;
padding:0 50px 20px;
background:linear-gradient(#fff,#FF94BB);
border:1px solid #ccc;
box-shadow:0 0 5px;
font-family:'Marcellus',serif;
float:left;
margin-top:10px
}
h1 {
text-align:center;
font-size:28px
}
hr {
border:0;
border-bottom:1.5px solid #ccc;
margin-top:-10px;
margin-bottom:30px
}
label {
font-size:17px
}
input {
width:100%;
padding:10px;
margin:6px 0 20px;
border:none;
box-shadow:0 0 5px
}
input#submit {
margin-top:20px;
font-size:18px;
background:linear-gradient(#22abe9 5%,#36caf0 100%);
border:1px solid #0F799E;
color:#fff;
font-weight:700;
cursor:pointer;
text-shadow:0 1px 0 #13506D
}
input#submit:hover {
background:linear-gradient(#36caf0 5%,#22abe9 100%)
}
Conclusion:
So, this was all about Inserting data in databaseĀ using codeigniter framework. keep following us to learn more.
83 Replies to “CodeIgniter Insert Data into Database”
Thank you very much for the sharing knowledge
Thanks for your appreciation !
Keep reading our blog posts.
thanx it help’s me very much
Thanks for your appreciation !
Keep reading our blog posts.
Thanks
Dear
Thanks for your appreciation !
Keep reading our blog posts.
tnxxxxxxxxxxxxxxxxxxxxx sir quite helpful……
Thanks for your appreciation !
Keep reading our blog posts.
I also want to upload the images of user ….Plzz tell me what changes required to do so ??
Here is the link for that : CodeIgniter Image Upload Via Library
https://www.formget.com/codeigniter-upload-image/
Cannot be able to integrate form of input and photo upload :/
I would to the form to add a link to a newly uploaded photo in the column “photo” of the new user…
hallo there how do i upload an image to a directory and its path to mysql database please assist me
Great tutorial. tks a lot!
Thank you so much for appreciation….
Keep reading our other blog posts…
hello
this code is working fine. it’s really nice work
can you plz help me to insert data using ajax in codeigniter
Hello Sohil,
Thank you so much for appreciation…
Yes we will get back to you with the solution in our upcoming blog posts…
sir
i cant’t able to connect with the database.I’ve created a db called company and table employee.After clicking submit it says that object not found.How i can fix the problem,iam a beginner in codeigniter too.
Hello Sarun,
What you have to do is… create database naming “college” and table naming “students”..
That will work for you….
Regards,
Swapnil
FormGet Team
i’ve created the above mentioned db but again got the same error.
Error msg,
“The requested URL was not found on this server. The link on the referring page seems to be wrong or outdated. Please inform the author of that page about the error.”
Very good tutorial. I am beginner in codeigniter and this tutorial found very useful for me.
Hello Kishor,
That sounds really great ! Keep reading our other blog posts for getting more coding tricks.
Regards,
FormGet Team
it’ll help another new bie if you provide link to download this program, any way thanks for tutorial i will try it
Hello Sid,
There is the option provided above for downloading the code , the download link will be sent in your mail id.
Regards,
FormGet Team.
Really helpful !! keep sharing !
Hello Benny,
That sounds really great ! Keep reading our other blog posts for getting more coding tricks.
Catch up new posts from here.
Regards,
FormGet Team
thanx very much guys! i appriciate
Hello Godson,
That sounds really great ! Keep reading our other blog posts for getting more coding tricks.
Catch up new posts from here
Regards,
FormGet Team
“Severity: Notice
Message: Undefined property: insert_ctrl::$db
Filename: core/Model.php
Line Number: 51”
I got this..
its in your controller……
public function __construct(){
parent:: __construct();
$this->load->model(‘avatardb’);//very important
//maybe you forgot to put this line
//avatardb there is the model filename
}
very very helpfull thank you so much
Thank you so much for explaining this THEN providing an example. I feel like I can finally store data in my database. I tried to use the Lynda course but the instructor makes no real attempt to help you find what is needed to learn more, or if you don’t understand how to learn it otherwise, and I felt so lost during the course. This will help me out so much.
How would you submit data to multiple tables in the database from the same form.
Hai,
I try your code.but its not working for .it produse the error
“A PHP Error was encountered
Severity: Notice
Message: Undefined property: insert_ctrl::$db
Filename: core/Model.php
Line Number: 51”
Fatal error: Call to a member function insert() on a non-object in E:Ashik Filewampwwwcodapplicationmodelsinsert_model.php on line 8
How to resolve these two error Please provide a help.
Thanks n regards
application/config/autoload.php to change this:
$autoload[‘libraries’] = array(‘database’);
$autoload[‘helper’] = array(‘html’, ‘form’, ‘url’);
working fine. check it once
I downloaded above code..but when i run this program..only title text shows..form element does not show.
When i run this project..put the all values on text box & click on submit button
then following error shows
A PHP Error was encountered
Severity: Notice
Message: Undefined property: insert_ctrl::$db
Filename: core/Model.php
Line Number: 51
This was AWESOME..THANKS! :=)
Correct Ur Database –> Student_Contact Field
It Should Be Student_Mobile
BTW Thank You š
i am working on a project build in codeigniter…i am not able to find the insertion code for the respective database..the records are inserted from other tables in the respecive database…
will u help me in this…?
Sir, PHP ERROR encounter here kindly give mie solution I am very beginner in CodeIgniter
thanks. it is so helpful
thanks
It’s really helpful….
ITS awesome i learn lots and lots of things from this article changing things into function moving it from one place to another superb work
very good thank you so much for knowledge sharing
thanks a lot
but what if i want to use select in my view
how i can do it ?? is it the same thing ??
Thanks in advance
Thank you so much! please keep updating this codeigniter parts.
You’re a life saver!!! Thnx a lot!!!
when i am executing the insert_ctrl page i am getting this error.
An Error Was Encountered
Unable to load the requested file: insert_view.php
what is this??
A PHP Error was encountered
Severity: Notice
Message: Undefined property: Insert_ctrl::$insert_model
Filename: controllers/insert_ctrl.php
Line Number: 30
Hello Shaikh Mujeeb,
Thanks for sharing your problem with us.
Now, we have updated our codes and itās reference.
For project installation, download code by giving Download URL and read PHPProjectInstall.pdf
Keep reading our other blog posts.. for getting more coding tricks.
Thanks & Regards,
FormGet.com
sir i want to ask , that my file does not take css,images etc , where i have to define my css folder in codegniter???
hello
this code is working fine. itās really nice work
can you plz help me to insert data using ajax in codeigniter
i tried this code but nothing is happened after submit the button,validation is working but i am not able to insert the data into database…i already congured the databse.php & imported your provided college.sql file in phpmy admin….hope you will help me as if i will get this insert then update,delete will become easy.
& is there any trick to check that the code is working or the part till it is working like we do in ajax or jquery that we add alert box at various places to know that till that part alert box is appearing means it is working till that code portion..
Thanks for Clear Code. I want more registration Form with ajax.
Thank you very much for the sharing knowledge.
this is very helpful for me.
where is database query ….?????????????
database query in Insert_ctrl.php file
Great Blog!! Kindly update the Password field also.
its better upload the db too. plz. i got error when submitting the form . š :/
hallo there this code information has been of great help to me, please allow me to ask a question, how do i upload image to a directory and the path of the same image to mysql database?
Thanks bro, for your so much helpful tutorial. Hope will get more helpful tutorial in future.Can we also ask for our needs?
it really work and valuable codes.
please try it , i just suggest that…
Hi, It’s really helpful. It is that I was looking from a long time. Delete and update articles also helpful.
Thanks for sharing useful information.
How to insert a video in the database using codeIgniter???
Easy and very effective…
thank you very mach……………
plsssssssssssssssssssssss tell me whats the problem in tha codeconnect_error)
{
die(“connection failed:”.$conn->connect_error)
}
else{
echo “connected sucessfully”;
}
$name=$_POST[‘name’];
$email=$_POST[’email’];
$specific time=$_POST[‘specific time’];
$class details=$_POST[‘class details’];
$gender=$_POST[‘gender’];
$sql=”INSERT INTO student(name, email, specific time, class details, gender)VALUES(‘$name’, ‘$email’, ‘$specific time’,’$class details’,’$gender’)”;
$result=mysql_query($sql);
if(&result->num_rows>0)
{
while ($row=$result->fetch_assoc())
{
echo”name”.$row[“name”].”email”.$_row[“email”].”specific time”.$_row[“specific time”].”class details”.$_row[“class details”].”gender”.$_row[“gender”].””;
}
else {
echo”0 result”;
}
}
$conn->close();
?>
die(āconnection failed:ā.$conn->connect_error)
}
else{
echo āconnected sucessfullyā;
}
$name=$_POST[ānameā];
$email=$_POST[āemailā];
$specific time=$_POST[āspecific_timeā];
$class details=$_POST[āclass_detailsā];
$gender=$_POST[āgenderā];
$sql=āINSERT INTO student(name, email, specific_time, class_details, gender)VALUES(ā$nameā, ā$emailā, ā$specific_timeā,ā$class_detailsā,ā$genderā)ā;
$result=mysql_query($sql);
if($result->num_rows>0)
{
while ($row=$result->fetch_assoc())
{
echoānameā.$row[ānameā].āemailā.$row[āemailā].āspecific timeā.$row[āspecific timeā].āclass detailsā.$row[āclass detailsā].āgenderā.$row[āgenderā].āā;
}
else {
echoā0 resultā;
}
}
$conn->close();
?>
Its too good. It helped to understand how to insert data into my mysql database. I am also expecting some wordpress tutorials like this. Thanks.
this is controlar cont.php
load->view(‘view’);
}
public function submit(){
$dbconnect = $this->load->database();
$this->load->model(‘mod’);
$data = array(
‘name’ => $this->input->get(‘name’),
’email’ => $this->input->get(’email’),
‘password’ => $this->input->get(‘password’),
);
$this->insert_model->form_insert($data);
$data[‘message’] = ‘Data Inserted Successfully’;
$this->load->view(‘view’);
}
}?>
next model mod.php
db->insert(‘tab’, $data);
}
}?>
next view.php
form
Welcome User
username:
email:
password:
data base name- basic
table-tab
name
email
password
why my data not insert in data base
hey Dont you use the form validation in this example i need a way to validate the form in Codeigniter.
The Mobile No. field is not in the correct format.
this always in the Mobile no. field, can you help me?
Great work. Very neat and helpful, but missing a few helpful tips, especially if you’re a complete newbie. Maybe an additional note on the modifications made inside the config, database, auto-load, and/or routes file. And on top of that I think there’s a problem with the regx-match function when used in CodeIgniter. It has something to do with the ‘pipe’ | which we use for separation. Other than that very good job. Thank you.
Its really amazing to work with codeigniter example. thanks a lot.
Please provide some tutorial insert delete update in zend framework2
CodeIgniter Platform is a fantastic PHP platform with an incredibly low impression, built for programmers who need a easy and excellent toolbox to create full-featured web applications. CodeIgniter was developed by EllisLab and is currently a company of the British Columbia Institute of Technology. This is a PHP MVC platform to easily build applications.
mail is not coming. thanks for the code by the way.