在foreach中插入ID

时间:2017-08-22 14:19:44

标签: php codeigniter foreach codeigniter-3 public

如何从简单插入ID中获取ID以及如何将其转发到Foreach?

控制器:

            public function insert_katogorie()
            {
                $this->Admin_model->insert_katogorie();
                redirect('admin/katogorie/');
            }

型号:

            public function insert_katogorie($katogorie_attribut = 0)
            {
                $data = array(  'tb_ygo_karten_kategorie_name' => $this->input->post('add_katogorie_name'),
                                );
                $this->db->insert('db_ygo_karten_kategorie', $data);
                foreach ($this->input->post('add_katogorie_attribut') as $katogorie_attribut)
                    {
                        $data = array(  //'tb_ygo_karten_kategorie_attribut_kategorie' => $data,
                                        'tb_ygo_karten_kategorie_attribut_attribut' => $katogorie_attribut,
                                        );
                        $this->db->insert('db_ygo_karten_kategorie_attribut', $data);
                    }
            }

2 个答案:

答案 0 :(得分:1)

我认为您正在寻找 last_insert_id 方法

你的模特:

public function insert_katogorie($katogorie_attribut = 0)
{
    $data = array(
        'tb_ygo_karten_kategorie_name' => $this->input->post('add_katogorie_name'),
    );

    $this->db->insert('db_ygo_karten_kategorie', $data);
    // returns the last insert id
    $last_insert_id = $this->db->insert_id();

    foreach ($this->input->post('add_katogorie_attribut') as $katogorie_attribut)
    {
        // you can use $last_insert_id inside this block

        $data = array(
            //'tb_ygo_karten_kategorie_attribut_kategorie' => $data,
            'tb_ygo_karten_kategorie_attribut_attribut' => $katogorie_attribut,
        );

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

}

参考:https://www.codeigniter.com/userguide3/database/helpers.html

答案 1 :(得分:0)

在任何变量中获取插入ID并在foreach循环中传递

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