1

I need to get the insert ID to be used in my controller, the problem is my model function has several data arrays, and I need the insert ID of the 1st array. therefor if I try to get the insert ID on my controller obviously its grabbing the 2nd insert ID and not the 1st.

I'm not sure this makes sense but here is an example:

Model

public function add() { 

    $data = array(
        'name' => $_POST['companyName']
        ,'type' => $_POST['companyType']
        ,'active' => '1');

    $this->db->insert('company', $data);

    $cid = $this->db->insert_id();

    $data2 = array(
        'cid' => $cid
        ,'name' => $_POST['locationName']
        ,'address' => $_POST['locationAddress']);

    $this->db->insert('locations', $data2);
}

This is working fine...However after this runs, on my controller the redirect is getting the data2 last insert which makes my redirect wrong.

Controller

public function add() {

    if (isset($_POST["add"]))
    {
        $this->Company_model->add();
        $id = $this->db->insert_id();
        redirect('company/view/'.$cid);
    }

    $data['states']  = $this->Company_model->

}

Any help would be greatful!

4

1 回答 1

3

你非常亲近。$id = $this->db->insert_id();您可以从模型方法中返回 $cid,而不是在控制器中重复。

模型

public function add()   { 
    $data = array(
        'name' => $_POST['companyName']
        ,'type' => $_POST['companyType']
        ,'active' => '1');
    $this->db->insert('company', $data);

    $cid = $this->db->insert_id();
    $data2 = array(
                   'cid' => $cid
                   ,'name' => $_POST['locationName']
                   ,'address' => $_POST['locationAddress']);
    $this->db->insert('locations', $data2);

    // This returns your first inserts id
    return $cid;
}

控制器

public function add() {

    if (isset($_POST["add"]))
    {
        $id = $this->Company_model->add();
        redirect('company/view/'.$id);
    }
    ...
于 2013-06-17T04:12:28.483 回答