i have 2 tables 'pengguna' and 'mahasiswa' and then 1 have a form which is 1 form inserting into 2 tables, so far i manage to insert the data but when it has to do with "primary key" and "foreign key" it has problem, as u can see from code below id_pengguna from table pengguna is a primary key and id_pengguna from table mahasiswa is a foreign key the problem is when i inserting the data, id_pengguna from pengguna has it value while in table mahasiswa it has no value, below are my code, is there any simple way or am i doing something wrong?
PENGGUNA TABLE
MAHASISWA TABLE

Controller
public function insertMahasiswa(){
$username = $this->input->post('username');
$password = md5($this->input->post('password'));
$data1 = array(
'username'=>$username,
'password'=>$password,
'level'=>3,
);
$nim = $this->input->post('nim');
$nama = $this->input->post('nama');
$email = $this->input->post('email');
$telepon = $this->input->post('telepon');
$data = array(
'nim'=>$nim,
'nama_mahasiswa'=>$nama,
'email'=>$email,
'telepon'=>$telepon,
);
$insert = $this->MMahasiswa->create('pengguna',$data1);
$insert1 = $this->MMahasiswa->create('mahasiswa',$data);
redirect(site_url('mahasiswa/data?balasan=1'));
}
MODEL
function create($table,$data){
$query = $this->db->insert($table, $data);
return $query;
}
You need to return last insert id form your model file
In model
function create($table,$data){
$query = $this->db->insert($table, $data);
return $this->db->insert_id();// return last insert id
}
In controller
$id_pengguna = $this->MMahasiswa->create('pengguna',$data1);
$data = array(
'nim'=>$nim,
'nama_mahasiswa'=>$nama,
'email'=>$email,
'telepon'=>$telepon,
'id_pengguna'=>$id_pengguna// add last insert id to mahasiswa table
);
$insert1 = $this->MMahasiswa->create('mahasiswa',$data);
Before inserting data to the 2nd table i.e. mahasiswa you need to grab the primary id created after insertion of data in table 1 (pengguna).
This can be done in 2 ways:
Grabbing last insert id using codeigniter's insert_id() function.
function create($table,$data) {
$query = $this->db->insert($table, $data);
return $this->db->insert_id(); } // return last insert id
After inserting the data in 1st table, get the id of the row which has the same username. (For this you must have unique usernames in username column) This will return the corresponding id.
Note: You can also do this with email column.
Source/Reference: Detailed explanation - Inserting data in 2 tables through 1 Form - CodeIgniter
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With