【问题标题】:How to store LAST_INSERT_ID() in database as foreign key in another table如何将数据库中的 LAST_INSERT_ID() 作为外键存储在另一个表中
【发布时间】:2014-12-23 11:33:47
【问题描述】:

我的要求是,有两个表用户和学生。

user table                          student table
id | email | user_type_id               id |    email   |name |user_id            

当学生提交表单数据时,应该将表格数据插入到两个表中。在用户表中,我存储 user_type_id =1 静态但在学生表中的 user_id 列中,应该保存生成的用户 ID。

我无法在学生表中保存用户 ID。这是我尝试过的代码

学生模型

public function add($data)
    {

        $temp = array(
            'Email' => $data['Email'],
            'user_type_id'=> 1
        );

        return $this->db->insert('users',$temp);
        return $this->db->insert_id();
        return $this->db->insert('students',$data);
    }

【问题讨论】:

  • 你可以使用触发器

标签: php mysql sql codeigniter


【解决方案1】:

使用

$this->db->insert_id()

公共函数添加($data) {

    $temp = array(
        'Email' => $data['Email'],
        'user_type_id'=> 1
    );

    return $this->db->insert('users',$temp);
    return $this->db->insert_id();
    $data['user_id'] = $this->db->insert_id(); // Use insert_id()
    return $this->db->insert('students',$data);
}

【讨论】:

  • 投票不同于选择答案作为解决方案。如果您看到反对我答案的投票箭头,则在其下方有白色右图。只需点击它,它就会变成绿色。就是这样。
猜你喜欢
  • 2018-07-19
  • 2021-07-05
  • 1970-01-01
  • 2012-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-17
  • 1970-01-01
相关资源
最近更新 更多