我偶然发现了一个关于我的朋友CI项目的问题:他想在主体上添加一个新的<input>
标签并插入MySQL,所以我制作了这段代码:
<?php echo form_open('welcome');?>
<div id="container">
<p id="add_field"><a href="#"><span>» Add Educational Background.....</span></a></p>
</div>
<div class="spacer"></div>
<input id="go" name="btnSubmit" type="submit" value="insert" class="btn" />
<?php echo form_close();?>
控制器:
$this->load->view('welcome_message');
$this->load->model('test');
if($this->input->post('attain',true) != null){
foreach ($this->input->post('attain',true) as $a) {
foreach ($this->input->post('major',true) as $m)
foreach ($this->input->post('school',true) as $s)
$data = array(
'attain'=>$a,
'major'=>$m,
'school'=>$s);
$this->db->insert('stress',$data);
print_r($data); // for show purposes
redirect(base_url());
}
}
Javascript:
<script type="text/javascript">
var count = 0;
$(function(){
$('p#add_field').click(function(){
count += 1;
$('#container').append(
'<input id="major' + count + '" name="attain[]' + '" type="text" />' +
'<input id="major' + count + '" name="major[]' + '" type="text" />' +
'<input id="' + count + '" name="school[]' + '" type="text" /><br />' );
});
});
</script>
这是用CodeIgniter编写的。
答案 0 :(得分:2)
互相嵌套的循环太多会导致数据库条目太多。
此外,重定向也在循环内部,因此只要第一次插入就会发生重定向
尝试:
if ($this->input->post('attain')) { // returns false if no property
$attain = $this->input->post('attain', true);
$schools = $this->input->post('school', true);
$major = $this->input->post('major', true);
foreach ($attain as $i => $a) { // need index to match other properties
$data = array(
'attain' => $a,
'major' => isset($majors[$i]) ? $majors[$i] : '',
'school' => isset($schools[$i]) ? $schools[$i] : ''
);
if (!$this->db->insert('stress', $data)) {
// quit if insert fails - adjust accordingly
print_r($data);
die('Failed insert');
}
}
// don't redirect inside the loop
redirect(base_url());
} else{
echo 'No Data';
}