In this example we are going to show you how to insert data in database using CodeIgniter framework PHP.
For insert data in MySQL using CodeIgniter first we have to create a table in data base.
The INSERT INTO statement is used to insert new data to a MySQL table:
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
To learn more about SQL, please visit our SQL tutorial.
For creating table the SQL query is:
SQL Query
CREATE TABLE crud (
`id` int(11) NOT NULL,
`first_name` varchar(30) NOT NULL,
`last_name` varchar(30) NOT NULL,
`email` varchar(30) NOT NULL,
PRIMARY KEY (id)
);
Here we using 3 files for insert data in MySQL:
- Crud.php Path: codeIgniter\application\controllers\Crud.php
- Crud_model.php Path: codeIgniter\application\models\Crud_model.php
- insert.php Path: codeIgniter\application\views\insert.php
Crud.php (Controller)
<?php
class Crud extends CI_Controller
{
public function __construct()
{
//call CodeIgniter's default Constructorparent::__construct();
//load database libray manually$this->load->database();
//load Model$this->load->model('Crud_model');
}
//Insertpublic function savedata()
{
//load registration view form$this->load->view('insert');
//Check submit button if($this->input->post('save'))
{
$first_name=$this->input->post('first_name');
$last_name=$this->input->post('last_name');
$email=$this->input->post('email');
$this->Crud_model->saverecords($first_name,$last_name,$email);
echo "Records Saved Successfully";
}
}
}
?>
Crud_model.php (Model)
<?php
class Crud_model extends CI_Model
{
//Insertfunction saverecords($first_name,$last_name,$email)
{
$query="insert into crud values('','$first_name','$last_name','$email')";
$this->db->query($query);
}
}
insert.php (View)
<!DOCTYPE html>
<html>
<head>
<title>Registration form</title>
</head>
<body>
<form method="post">
<table width="600" border="1" cellspacing="5" cellpadding="5">
<tr>
<td width="230">First Name </td>
<td width="329"><input type="text" name="first_name"/></td>
</tr>
<tr>
<td>Last Name </td>
<td><input type="text" name="last_name"/></td>
</tr>
<tr>
<td>Email ID </td>
<td><input type="email" name="email"/></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" name="save" value="Save Data"/></td>
</tr>
</table>
</form>
</body>
</html>
Run the program on your browser with URL:
http://localhost/codeIgniter/index.php/Crud/savedata
Here codeIgniter is my folder name. Put your folder name instead of codeIgniter.Rest of things are same.
0 comments:
Post a Comment
Thanks