Inserting Data to Database using CodeIgniter
0 3401
- To insert data into the database, we have to be connected with the database. In the previous blog, we have learned how to make a connection with the database.
Related Topic:
Connecting Database
Codeigniter Interview Questions
Inserting Data into Database:
There are several steps to insert data into the database.
Step 1 Create a table into the database in which you want to insert data.
Step 2 Create a view file insert_view.php in the application/views directory.
insert_view.php
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>Insert Data Form</h2>
<form method="post" enctype="multipart/formdata">
<div class="form-group">
<label for="email">Name:</label>
<input type="text" class="form-control" name="name" placeholder="Enter Name">
</div>
<div class="form-group">
<label for="pwd">Roll Number:</label>
<input type="text" class="form-control" name="roll_number" placeholder="Enter Roll Number">
</div>
<div class="form-group">
<label for="pwd">Class:</label>
<input type="text" class="form-control" name="class" placeholder="Enter Class">
</div>
<input type="submit" name="insert" class="btn btn-success" value="Submit"/>
</form>
</div>
</body>
</html>
Step 3 Create a model file Crud_model.php in the application/models directory.
Crud_model.php
<?php
class Crud_model extends CI_Model
{
function insert_data($name,$roll_number,$class)
{
$query="insert into `student` values('','$name','$roll_number','$class')";
$this->db->query($query);
}
}
Step 4 Create a controller file Crud_controller.php in the application/controllers directory.
Crud_controller.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed') //for secuirty
public function insert_fun()
{
//load database
$this->load->database();
//load Model
$this->load->model('Crud_model');
//load view
$this->load->view('insert_view');
// after submission code
if($this->input->post('insert'))
{
$name=$this->input->post('name');
$roll_number=$this->input->post('roll_number');
$class=$this->input->post('class');
$this->Crud_model->insert_data($name,$roll_number,$class);
echo "Data inserted Successfully";
}
}
}
?>
Related Topics:
Views in CodeIgniter
Models in Codeigniter
Helpers in Codeigniter
Step 5 Now, go to the browser and enter the following URL to insert data.
http://localhost/ci/index.php/Crud_controller/insert_fun
Now, you find a form. Fill the form and submit it to get a result.
Share:
Comments
Waiting for your comments