Insert data into database using codeigniter

Date posted: 04-oct-2018

Please follow  the steps to insert data into database using codeigniter

Step 1: Create a new file under the path Application/controllers/Insert.php.Copy the below given code in your view.

<?php
class Insert extends CI_Controller 
{
	public function __construct()
	{
	//call CodeIgniter's default Constructor
	parent::__construct();
	
	//load database libray manually
	$this->load->database();
	
	//load Model
	$this->load->model('Insert_Model');
	}
 
	public function savedata()
	{
		//load registration view form
		$this->load->view('registration');
	
		//Check submit button 
		if($this->input->post('save'))
		{
		//get form's data and store in local varable
		$n=$this->input->post('name');
		$e=$this->input->post('email');
		$m=$this->input->post('mobile');
		
//call saverecords method of Insert_Model and pass variables as parameter
		$this->Insert_Model->saverecords($n,$e,$m);		
		echo "Records Saved Successfully";
		}
	}
}
?>

Step 2: Create a new file under the path Application/views/registration.php. Copy the below given code in your 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">Enter Your Name </td>
    <td width="329"><input type="text" name="name"/></td>
  </tr>
  <tr>
    <td>Enter Your Email </td>
    <td><input type="text" name="email"/></td>
  </tr>
  <tr>
    <td>Enter Your Mobile </td>
    <td><input type="text" name="mobile"/></td>
  </tr>
  <tr>
    <td colspan="2" align="center"><input type="submit" name="save" value="Save Data"/></td>
  </tr>
</table>

  </form>
</body>
</html>

Step 3: Create a new file under the path Application/models/Insert_Model.php. Copy the below given code in your model.

<?php
class Insert_Model extends CI_Model 
{
  function saverecords($name,$email,$mobile)
  {
  $query="insert into users values('','$name','$email','$mobile')";
  $this->db->query($query);
  }
}

 

Leave a Reply