CodeIgniter:如何将具有一个名称和多个选择框的数据插入第二个 table?

CodeIgniter: How to Insert data with one name and multiple selectbox into the second table?

有一张登记表,该表上有 5 个字段。其中之一是增加爱好。这个字段是一个选择框,当用户想要添加多个爱好时,有一个 + 按钮可以生成一个新的选择框来添加第二个等等。

例如:

  Name:
  Surname:
+ Hobbies: Select One
           -fishing
           -shopping
           -etc.

单击加号时,会出现一个新的选择框。

  Name:
  Surname:
  Hobbies: fishing
           -shopping
           -etc.
+ Hobbies: Select One
           -shopping
           -etc.

所以选择框的代码如下。

我的查看文件

<?php
    echo '<select name="hobby_id[]" class="select2" data-allow-clear="true" data-placeholder="Select One">';
         echo '<option></option>';
         echo '<optgroup label="Hobby List">';
                foreach($hobbies as $hobby_item)
                {
                    echo '<option value="'.$hobby_item->hobby_id.'">'.$hobby_item->hobby_name.'</option>';
                }
         echo '</optgroup>';
    echo '</select>';
?>

我想从多个同名的选择框中插入数据。但是在我的模型文件中,我不确定如何使用它。我的 model.php

$this->db->set('name',  $this->input->post('name')); 
$this->db->set('surname',   $this->input->post('surname')); 
$this->db->set('phone',     $this->input->post('phone')); 
$this->db->set('mail',  $this->input->post('mail')); 

$this->db->insert('users'); 

$this->db->set('user_id',  $this->db->insert_id());
$this->db->set('hobby_id', $this->input->post('hobby_id'));

$this->db->insert('hobbies');

我尝试做的视图如下所示。

user_id | hobby_id
   1          1
   2          1
   2          2

我想用同名的选择框添加多行。但是不知道模型文件里怎么写。你可以帮帮我吗?你能告诉我我可以在互联网上搜索的技巧吗?或者你有一个简单的例子可以分享一下。

您将获得一系列关于兴趣爱好的值。 因此,对于兴趣爱好,请在 user insert query :

之后在您的模型中尝试此操作
$insert_id = $this->db->insert_id();
$hobby_ids = $this->input->post('hobby_id');
if(count($hobby_ids) > 0){
  for($i=0;$i<count($hobby_ids);$i++) {
    $this->db->set('user_id', $insert_id );
    $this->db->set('hobby_id',$hobby_ids[$i]);
    $this->db->insert('hobbies');
  }
}