CodeIgniter 使用 jquery 动态输入并插入到数据库

GOD*_*ODZ 5 javascript php mysql jquery codeigniter

我偶然发现了一个关于我的朋友 CI 项目的问题:他想<input>在正文中添加一个新标签并插入到 MySQL,所以我制作了以下代码:

<?php echo form_open('welcome');?>
<div id="container">
    <p id="add_field"><a href="#"><span>&raquo; 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();?>
Run Code Online (Sandbox Code Playgroud)

控制器:

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

            }

        }
Run Code Online (Sandbox Code Playgroud)

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> 
Run Code Online (Sandbox Code Playgroud)

这是用 CodeIgniter 编写的。

cha*_*tfl 4

相互嵌套的循环太多,这会导致数据库条目太多。

此外,重定向位于循环内部,因此一旦进行第一次插入,就会发生重定向

尝试:

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';
}
Run Code Online (Sandbox Code Playgroud)