Search code examples
phphtmlmysqlcodeigniter-4

How to insert data into 2 tables in Codeigniter 4


I have 3 tables, 2 tables (groups and users) and 1 table for the relation between groups and users (users_groups).

Table groups:

  • id (primary key) AI
  • name_unit

Tables users:

  • id (primary key) AI
  • first_name
  • email

Table users_groups:

  • id(primary key) AI
  • user_id(FK)
  • group_id(FK)

i have one form to input name_user, email and group_id. But, its just added into table users only.

Model code:

public function saveAdmin($data_user, $data_group){
        return $this->db->table('users')->insert($data_user);

        $data_group['user_id'] = $this->db->insertID();
        return $this->db->table('users_groups')->insert( $data_group);
    }

Controller

public function save()
    {
        $data_user = array(
            'first_name'        => $this->request->getPost('first_name'),
            'email'             => $this->request->getPost('email'),
            'password'          => $this->request->getPost('password')
        );
      
        $data_group = array(
            'group_id'    => $this->request->getPost('group_id')
        );    
      
        $this->userModel->saveAdmin($data_user, $data_group);
        return redirect()->to(base_url('SAdmin/dataAdmin'));
    }

View

<form action="<?= base_url('SAdmin/DataAdmin/save'); ?>" method="post">
 <label class="col-sm-4 col-form-label">Nama</label>
 <input type="text" class="form-control" id="first_name" placeholder="Nama">
                                     
 <label class="col-sm-4 col-form-label">Email</label>
 <input type="text" class="form-control" name="email" placeholder="Email">
    
 <label class="col-sm-4 col-form-label">Unit</label>
 <select name="group_id" class="form-control">
  <option value="">-Pilih-</option>
  <?php foreach($unitadmin as $row):?>
  <option value="<?= $row['id'];?>"><?= $row['description'];?></option>
 <?php endforeach;?>
 </select>

</form>

I want the data added into users_group and users, what should i do? Thanks before


Solution

  • You used return keyword before complete your full task on your Model. So, you need to change your Model with this code.

     public function saveAdmin($data_user, $data_group) {
          $this->db->table('users')->insert($data_user);
          $data_group['user_id'] = $this->db->insertID();
          return $this->db->table('users_groups')->insert( $data_group);
      }