Debujang Debujang - 3 months ago 10
MySQL Question

How to get the latest inserted table id in codeigniter?

I have this function in my controller, this is used for insert data to database mysql.

public function tambah()
{
$data = array(
'elektronik_nama' => $this->input->post('elektronik_nama'),
'elektronik_kode' => $this->input->post('elektronik_kode'),
'elektronik_merk' => $this->input->post('elektronik_merk'),
'elektronik_lokasi' => $this->input->post('elektronik_lokasi'),
'elektronik_tahun_pengadaan' => $this->input->post('elektronik_tahun_pengadaan'),
'elektronik_sbr_perolehan' => $this->input->post('elektronik_sbr_perolehan'),
'elektronik_kondisi' => $this->input->post('elektronik_kondisi'),
'elektronik_harga' => $this->input->post('elektronik_harga'),
);

$data_tronik = $this->in_elektronik_model->tambah_data($data);

$data_tronik_mebel = array(
'semua_aset_id_aset' => $data_tronik,
'semua_aset_nama' => $this->input->post('elektronik_nama'),
'semua_aset_kode' => $this->input->post('elektronik_kode'),
);

$this->in_semua_aset_model->tambah_data($data_tronik_mebel);
}


and i have two models to insert data

class In_elektronik_model extends CI_Model {

function tambah_data($data)
{
$this->db->insert('in_elektronik',$data);
}
}


and

class In_semua_aset_model extends CI_Model {

function tambah_data($data)
{
$this->db->insert('in_semua_aset', $data);
}
}


i assumed that
'semua_aset_id_aset' => $data_tronik,
will give primary key from in_elektronik_model, but the result give NULL to in_semua_aset_model.
How to get primary key from in_elektronik_model?

Answer

Is the primary key the insert id? In that case:

class In_elektronik_model extends CI_Model {

     function tambah_data($data)
    {
         $this->db->insert('in_elektronik',$data);
         $inserted_id = $this->db->insert_id();
         return $inserted_id;
    }
}