Codeigniter Insert Multiple Rows in SQL

可紊 提交于 2019-11-29 04:17:45

Make your form like this:

<tr>
    <td><input type="text" name="user[0][name]" value=""></td>
    <td><input type="text" name="user[0][address]" value=""><br></td>
    <td><input type="text" name="user[0][age]" value=""></td>
    <td><input type="text" name="user[0][email]" value=""></td>
</tr>
<tr>
    <td><input type="text" name="user[1][name]" value=""></td>
    <td><input type="text" name="user[1][address]" value=""><br></td>
    <td><input type="text" name="user[1][age]" value=""></td>
    <td><input type="text" name="user[1][email]" value=""></td>
</tr>

Then you can simply do:

foreach($_POST['user'] as $user)
{
    $this->db->insert('mytable', $user);
}

Multiple insert/ batch insert is now supported by codeigniter. It will firing one query rather than firing too many queries.

$data =array();
for($i=0; $i<$count; $i++) {
$data[$i] = array(
           'name' => $name[$i], 
           'address' => $address[$i],
           'age' => $age[$i],
           'email' => $email[$i],

           );
}

$this->db->insert_batch('mytable', $data);

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;$y<count($person);$y++){
    $this->db->insert('mytable',$person[$y];
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!