Codeigniter Insert Multiple Rows in SQL

前端 未结 3 2169
闹比i
闹比i 2020-12-16 04:16

I am fresh to Codeigniter. I have a form which looks something like this.


<         


        
3条回答
  •  我在风中等你
    2020-12-16 04:35

    The form you show will create a $_POST array with indexes of name, address, age, and email. Each of these will contain the n number of "rows" your form provides. For example:

    array(
        'name' => array('First Name','Second Name'),
        'address' => array ('First Address','Second Address'),
        'age' => array('First Age','Second Age'),
        'email' => array('First Email', 'Second Email')
        );
    

    You may want to rearrange that array into one where each index of the array is a "person". This will make inserting the information into your database simpler.

    //subtract 1 from below to account for the assumed submit button
    $number_of_rows = count($_POST)-1;
    
    for($i=0;$i<$number_of_rows;$i++){
        $person[]['name'] = $this->input->post('Name')[$i];
        $person[]['address'] = $this->input->post('Address')[$i];
        $person[]['age'] = $this->input->post('Age')[$i];
        $person[]['email'] = $this->input->post('Email')[$i];
        }
    

    This will create something like this:

    array(
        0=>array('First Name','First Address','First Age','First Email'),
        1=>array ('Second Name','Second Address','Second Age','Second Email') 
        );
    

    Now you can use a loop to insert each person into the db.

    for($y=0;$ydb->insert('mytable',$person[$y];
    }
    

提交回复
热议问题