php - 代码点火器 : inserting data/record into 2 tables

标签 php codeigniter

我有 2 个表“pengguna”和“mahasiswa”,然后 1 个有一个表单,其中 1 个表单插入到 2 个表中,到目前为止我设法插入数据但是当它与“主键”和“外键”它有问题,正如你从下面的代码中看到的那样 id_pengguna 来自表 pengguna 是一个主键id_penggunamahasiswa 中的 是一个外键 问题是当我插入数据时,pengguna 中的 id_pengguna 有它有值(value),而在表 mahasiswa 中它没有值(value),下面是我的代码,有什么简单的方法还是我做错了什么?

彭古纳 table enter image description here 马哈西瓦表 enter image description here

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;
}

最佳答案

您需要从您的模型文件中返回最后插入的 id

在模型中

function create($table,$data){
    $query = $this->db->insert($table, $data);
    return $this->db->insert_id();// return last insert id
}

在 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);

关于php - 代码点火器 : inserting data/record into 2 tables,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36709801/

相关文章:

php - code igniter 模块化扩展 - 对 MX_Router::_set_default_controller() 的访问级别必须是公共(public)的(如在 CI_Router 类中)

php - 使用 Web 服务的 Codeigniter 分页

php - 如何在下拉列表中获取所选选项的ID?

javascript - 使用 Ajax 在提交表单时保持在同一页面上不起作用

php函数定义中的 "database"关键字是什么

php - Mysql php,不同项目类型不同表

php - CodeIgniter 即时更改默认数据库名称

php - 嵌套选择框

php - 使用 PHP PDO 从 CSV 错误插入循环

javascript - 单击菜单下 zipper 接触发提交表单