Neha
Neha

Reputation: 13

how to create insert function in model

In controller I am sending data like that :

$data=array[
    'table'=>'ci',
    'where'=>'',
    'val'=>['name'=>$name,
        'pass'=>$pass,
        'mobile'=>$mobile,
        'date'=>$date,
        'status'=>$status
    ]
];
$this->load->model('show_model');
$this->show_model->insert_data($data);

In the model code I have:

<?php
class show_model extends CI_model{

    public function insert_data($data){
    }
}    
?>

I want to create a function to data in ci table what is the method to get the data from the controller and how can i make the funcyion for insert for what i am sending the data.

Upvotes: 1

Views: 1016

Answers (2)

Mudassar Khani
Mudassar Khani

Reputation: 1479

I think you are trying to perform insert operation but you couldn't figure it out. Lets take it step by step. Codeigniter has a database library which comes with installation. You can load that library in config->autoload.php and provide database credentials in config->database.php. All set!

Once you have loaded database library you can use bunch of database function. E.g

For Insertion

 $this->db->insert('table_name',data);
 // Your data can be array of the data you want to insert

Let's say you want to send data from your controller to your Model to save it to db you can do something like this

 Class Controller_Name extends CI_Controller {
      public function __construct(){
          parent::__construct();
          $this->load->model('your_model');
      }

      public function index() {
          $data=array(
                      'username' => 'Your Name',
                      'email'    => 'Your Email',
                      'password' => 'Your Password'
                );
          // Send it to DB
          $this->your_model->save_data($data);
          // Show success
          echo 'Data Saved';
      }
 }

Now in your Model you will have the function save data like this

 Class Your_model extends CI_Model {
      public function __construct(){
          parent::__construct();
      }

      public function save_data($data){
          // Assuming the table name is users
          $this->db->insert('users',$data);
      }
 }

You can do a lot of modifications and enhancements, there is a lot of learning ahead but this is a fair start.

Upvotes: 1

Amaan Iqbal
Amaan Iqbal

Reputation: 761

Try

public function insert($data) {

    if($this->db->insert('table_name', $data)) {

         //Success

    }
}

Ensure you are connected to your database from database.php in application/config folder

Hope it helps

Upvotes: 0

Related Questions