简体   繁体   English

如何获取和插入 ID CodeIgniter

[英]How to get and insert ID CodeIgniter

I save my data like this我像这样保存我的数据

public function saveInvestors($id = 0)
{
    $data = array ('id' => $id );
    $data2 = array ('ref_id' => $data['id]);

    if ($id == 0) 
    {
       return [$this->db->insert('investor', $data), $this->db->insert('leveling', $data2)];
    }
}

my id on $data is auto increment on database while id on $data2 is not my problem here is that I couldn't get the id on $data and insert it on leveling but it always returning 0我在$data上的id在数据库上是自动递增的,而在$data2上的id不是我的问题,我无法在$data上获取id并将其插入到调平中,但它总是返回 0

You need to get the inserted id after inserting it into the database:插入数据库后需要获取插入的id:

$this->db->insert('investor', $data);
$new_id = $this->db->insert_id();

As seen in the documentation: https://codeigniter.com/user_guide/database/helpers.html如文档中所示: https://codeigniter.com/user_guide/database/helpers.html

Try this.尝试这个。

    public function saveInvestors($id = 0)
{
    $data = array('id' => $id);
    if ($id == 0) {
        $this->db->trans_begin();
        $this->db->insert('investor', $data);
        $id_investor = $this->db->insert_id();

        $data2 = array('ref_id' => $id_investor);
        $this->db->insert('leveling', $data2);

        if ($this->db->trans_status() === TRUE) {
            $this->db->trans_commit();
            return TRUE;
        } else {
            $this->db->trans_rollback();
            return FALSE;
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM