Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
921 views
in Technique[技术] by (71.8m points)

mysql - Codeigniter Insert Multiple Rows in SQL

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>

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's answer looks better but is currently throwing a lot of errors.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...