为每个数组值插入行(复选框值)代码点火器

时间:2016-03-18 11:54:24

标签: php mysql arrays codeigniter

我有这个视图,为我的数据库中的每一行输出一个复选框,它完全正常。

<div class="box-body">
    <div class="form-group">
        <label class="col-sm-2 control-label col-sm-offset-2" >CheckBox:</label>
            <div class="col-sm-5">
               <div class="form-group">
                 <?php foreach($content1 as $cb){ ?>
                    <div class="checkbox">
                      <label>
                        <input type="checkbox" name="h[]" value = "<?php echo $cb->USERCODE?>">
                        <?php echo $cb->DEPARTMENT.' '.$cb->USERTYPE?>
                      </label>
                     </div>
                <?php } ?>
             </div>
        </div>
    </div>
</div>

如果我print_r它已经在数组中有它的值,例如:

Array ( [0] => 2 [1] => 3 [2] => 6 [3] => 7 [4] => 4 [5] => 5 [6] => 1 )

现在我想要实现的是每个被检查的值,它将进入数据库。例如,我只为组POSTVALUE选择了值,我输入的是输入类型=&#34; text&#34;。

 Array ( 
[0] => 2 
[1] => 3 
[2] => 4  )

我的模型将查询

insert into table column , column1 values '2' , 'POSTVALUE';
insert into table column , column1 values '3' , 'POSTVALUE';
insert into table column , column1 values '4' , 'POSTVALUE';

2 个答案:

答案 0 :(得分:2)

提交值后,将该值从控制器传递给模型函数。 在控制器中使用此功能。

public function form_action()
{

    $h= $this->input->post('h');
    $data=array(
    'postvalue' => $this->input->post('postvalue'),
    'h' => $h
    );
  $this->model_name->insert_value($data);
}

这是您的样本模型函数。这对你有帮助。

public function insert_value($data)
{        
    $n =0;
    foreach($data['h'] as $rows) {
        $data[$n] = array(
        'column' => $rows,
        'column1' => $data['postvalue'],
        );
        $query = $this->db->insert('table_name',$data[$n]);
        $n++;
    }


    if($query)
    {

        return true;
    }
    else
    {
        return false;
    }
}

答案 1 :(得分:2)

您的模型应如下所示

您可以尝试使用简单的插入

function insert_checkbox($array){
    foreach ($array as $row){
      $data = ['column'=>$row];
      $this->db->insert('table', $data); 
    }
}

您也可以尝试使用insert_batch()

function insert_checkbox($array){
    $data = [];
    foreach ($array as $row){
      $data[] = ['column'=>$row];
    }
    $this->db->insert_batch('table', $data); 
 }

查看文档here