【问题标题】:How to insert a dynamic form values into database in php如何在php中将动态表单值插入数据库
【发布时间】:2018-07-23 07:36:10
【问题描述】:

如何将表单值(动态复选框,输入)动态插入数据库 这是我的视图文件:

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

这是我的控制器功能:

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

当我打印这个数组 $fields 时,它显示为:

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

这是我的表单:动态显示的 menuid 和菜单 desc 和复选框。我需要像下面显示的表单一样插入表格。

【问题讨论】:

  • 您是否收到错误消息?是否插入了错误的值?有没有插入东西?
  • 您必须遍历您的帖子值然后插入数据,因为所有表单值都在数组中
  • 不,我没有收到任何错误,但我想像上面提到的图像一样插入数据库

标签: php codeigniter


【解决方案1】:

您需要遍历数组。您可以使用菜单 ID 作为键,因为它是连续的,例如menu_id 的第一个对应于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);
}

【讨论】:

  • 你能帮我检查一下吗?在您的示例中,您的复选框正在返回“打开”。您可能知道,如果未选中复选框,则它不会提交 anything 因此它可能会弄乱订单并在我的答案中被错误地分配。根据您的值,它应该返回 menu_id 的值吗?但它没有???
  • 在任何情况下,如果您可以让复选框在选中时报告 menu_id,您可以简单地修改我的代码,如下所示:$yes = array_flip($this-&gt;input-&gt;post('yes'));
  • 但出现警告错误消息:array_flip() 期望参数 1 为数组,给定为空
  • 我的坏$yes = $this-&gt;input-&gt;post('yes'); $yes = is_null($yes) ? array() : array_flip($yes);
  • 但如果未选中该复选框,则会将 false 存储到表中。(我回复:你能帮我检查一下吗?)
猜你喜欢
  • 2013-07-09
  • 1970-01-01
  • 2013-12-18
  • 2014-04-20
  • 1970-01-01
  • 1970-01-01
  • 2016-08-07
  • 2018-01-28
  • 2019-02-15
相关资源
最近更新 更多