How to insert data into database in Codeigniter

Intro: 

In this instance, we’re going to present to you how one can insert knowledge in a database utilizing CodeIgniter framework PHP.

To insert knowledge in MySQL utilizing CodeIgniter firs, wee have to create a desk in the knowledge base.

Right here we utilizing 3 information for insert knowledge in MySQL:

  • php Path: codeIgniter\application\controllers\Crud.php
  • php Path:
  • codeIgniter\application\models\Crud_model.php
  • php Path: codeIgniter\application\views\insert.php

Crud.php (Controller)

<?php

class Crud 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(‘Crud_model’);

     }

        /*Insert*/

     public function savedata()

     {

          /*load registration view form*/

          $this->load->view(‘insert’);

    

          /*Check submit button */

          if($this->input->post(‘save’))

          {

              $data[‘first_name’]=$this->input->post(‘first_name’);

              $data[‘last_name’]=$this->input->post(‘last_name’);

              $data[’email’]=$this->input->post(’email’);

              $response=$this->Crud_model->saverecords($data);

              if($response==true){

                      echo “Records Saved Successfully”;

              }

              else{

                        echo “Insert error !”;

              }

          }

     }

    

}

?>

 

Crud_model.php (Model)

<?php

class Crud_model extends CI_Model

{

    

     function saverecords($data)

     {

        $this->db->insert(‘crud’,$data);

        return true;

     }

    

}

 

insert.php (View)

<!DOCTYPE html> 

<html>

<head>

<title>Registration form</title>

</head>

 

<body>

     <form method=”post” action=”<?= base_url() ?>Crud/savedata”>

          <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>

Add a Comment

Your email address will not be published. Required fields are marked *