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);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)