bothsa24312
bothsa24312

Reputation: 3

Codeigniter 2.0 how to insert records in two tables

I have these two tables('users','users2') I want to insert data in my two tables. What would be the best approach? using array?

My Model code is :

function user_add($option){
      $this->db->set('userid',$option['user_id']);
      $this->db->set('email', $option['email']);
      $this->db->set('password', $option['pw']);
      $this->db->set('created', 'NOW()', false);
      $this->db->insert('users');
      //users2 tables
      $this->db->set('user_id',$option['user_id']);
      $this->db->insert('users2');
  }

Upvotes: 0

Views: 338

Answers (2)

Abdulla Nilam
Abdulla Nilam

Reputation: 38584

Create 2 functions in controller.

  1. for insert table 01
  2. for insert table 02

It is not good practice to use two methods in one model function

In Controller

public function method_name
{
    $this->Model_name->user_add_table1($option);
    $this->Model_name->user_add_table2($option);
}

In Model

function user_add_table1($option){
    $this->db->set('userid',$option['user_id']);
    $this->db->set('email', $option['email']);
    $this->db->set('password', $option['pw']);
    $this->db->set('created', 'NOW()', false);
    $this->db->insert('users');
}
function user_add_table2($option){
    $this->db->set('userid',$option['user_id']);
    $this->db->set('email', $option['email']);
    $this->db->set('password', $option['pw']);
    $this->db->set('created', 'NOW()', false);
    $this->db->insert('users');
}

Upvotes: 1

acupofjose
acupofjose

Reputation: 2159

You can do it like that, or via array

$array = array(
    'userid' => $option['user_id'],
    'email' => $option['email'],
    'password' => $option['password'],
    'created' => time(),
);

$this->db->set($array);
$this->db->insert('users');

$this->db->set($array);
$this->db->insert('users2');

Using the array, you can reuse the variable as much as you want, including array manipulations to remove or add keys.

Upvotes: 3

Related Questions