Codeigniter 在 SQL 中插入多行

我对 Codeigniter 很陌生.我有一个看起来像这样的表格.

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

<tr>
<td><input type="text" name="Name[0]" value=""></td>
<td><input type="text" name="Address[0]"  value=""><br></td>
<td><input type="text" name="Age[0]" value=""></td>
<td><input type="text" name="Email[0]" value=""></td>
</tr>



<tr>
<td><input type="text" name="Name[1]" value=""></td>
<td><input type="text" name="Address[1]"  value=""><br></td>
<td><input type="text" name="Age[1]" value=""></td>
<td><input type="text" name="Email[1]" value=""></td>
</tr>

可能有 0 到 n 行,通常是 5 到 10 行.如何在 SQL 中插入它们?这可以用 Codeigniter 还是我应该使用本机 PHP 脚本?

There may be from 0 to n rows, usually 5 to 10 rows. How do I insert them in SQL? Is this possible with Codeigniter or should I use a native PHP script?

$name=$_POST['Name'];
$address=$_POST['Address'];
$age=$_POST['Age'];
$email=$_POST['Email'];
$count = count($_POST['Name']);



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

           );


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

我做到了.有用.但解决方案似乎不够优雅.

I did this. It works. But the solution seems inelegant.

kevtrout 的答案看起来更好,但目前抛出了很多错误.

kevtrout's answer looks better but is currently throwing a lot of errors.

有没有办法一次性插入所有数据?

Is there any way to insert all data at one go?

推荐答案

让你的表单像这样:

<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>

然后你可以简单地做:

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

相关文章