dongtiao2976 2018-07-23 07:36
浏览 196
已采纳

如何在php中将动态表单值插入数据库

how to insert form values(dynamic checkbox,input) dynamically into database This my view file:

<form action="<?php base_url('controller/insert'); ?>"> 
    <table>
        <thead>
            <tr> 
                <th>Menu Id</th> 
                <th>Menu Name</th> 
                <th>Yes/No</th> 
            </tr> 
        </thead>
        <tbody>
            <?php foreach($result as $res) { ?>
                <tr> 
                    <td><input type="text" name="menu_id[]" value="<?= $res->menu_id ?>"></td> 
                    <td><input type="text" name="menu_name[]" value="<?= $res->menu_name ?>"></td> 
                    <td><input type="checkbox" name="yes[]" value="<?= $res->menu_id ?>"></td> 
                </tr> 
            <?php } ?>
        </tbody>
    </table>
</form>

this my controller function:

<?php
    $fields = array(
        'menu_id'   => $this->input->post('menu_id'),
        'menu_name' =>  $this->input->post('menu_name'),
        'yes'       =>$this->input->post('yes')
    );
    $this->db->insert('menu_table',$fields);
?>

when i print this array $fields it displays as:

Array ( [0] => 2 [1] => 3 ) Array ( [0] => Plant [1] => Line ) Array ( [0] => on [1] => on ).

this my form:the menuid and menu desc and checkbox displaying dynamically.i need to insert into table as same as the form below displays. enter image description here

  • 写回答

1条回答 默认 最新

  • duanbairan4235 2018-07-23 07:52
    关注

    You need to loop through the arrays. You can use the menu id as the key as it is sequential e.g. the first of menu_id corresponds with the first of menu_name:

    $menu_id = $this->input->post('menu_id');
    $menu_name = $this->input->post('menu_name');
    $yes = $this->input->post('yes');
    
    $yes = is_null($yes) ? array() : array_flip($yes);
    
    if (is_null($menu_id) || is_null($menu_name)) {
        show_error('Parameters missing');
    }
    
    // should really be in a model
    foreach ($menu_id as $key => $value) {
        $data['menu_id'] = $value;
        $data['menu_name'] = $menu_name[$key];
        $data['yes'] = isset($yes[$value]) ? 'true' : 'false';
        $this->db->insert('menu_table',$data);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?