使用codeigniter通过foreach在MySQL中保存多个复选框数据

时间:2013-09-17 08:47:41

标签: php mysql codeigniter

我有两张桌子::: tbl_product和tbl_featured_product。我确实通过复选框系统查看了查看页面中的所有产品(来自tbl_product)信息。这样我就可以根据需要通过检查将数据提交到tbl_featured_product。

我可以在复选框中查看查看页面的所有信息。但是无法将它们保存在数据库中。只保存最后一行。请帮助我同时保存多个数据:::

视图:::

<?php foreach($all_product as $values) { ?>

  <input type="checkbox" name="product_name[]" value="<?php echo $values->product_name;?>" /> <?php echo $values->product_name;?> <br>
  <input hidden="hidden" name="product_id[]" value="<?php echo $values->product_id;?>" /> 
  <input hidden="hidden" name="product_price[]" value="<?php echo $values->product_price;?>" /> 

<?php } ?>

<input type="submit" name="btn" value="Save">

我的控制器:::::

 public function save_featured_product()
 {
    $data=array();

    if ($this->input->post()) {
        $data['featured_id']=$this->input->post('featured_id',true);
        $data['product_id']=$this->input->post('product_id',true);
        $data['product_name']=$this->input->post('product_name',true);
        $data['product_price']=$this->input->post('product_price',true);

        $this->sa_model->save_featured_product_info($data);

        $sdata=array();
        $sdata['message']='Save product Information Successfully !';
        $this->session->set_userdata($sdata);
        redirect('super_admin/add_featured_product');
    } 

我的模特::::

 public function save_featured_product_info($data)
  {
    $this->db->insert('tbl_featured_products',$data);
  }

请告诉我您方的解决方案。谢谢

3 个答案:

答案 0 :(得分:0)

您的问题是输入$this->input->post('product_name')是数组,因此您需要为每个插入一行,例如:

(在模型中)

public function save_featured_product_info($data)
{
if (isset($data['product_name']) && is_array($data['product_name'])):
    foreach ( $data['product_name'] as $key=>$value ):
        $this->db->insert('tbl_featured_products', array(
           'product_id'=>$data['product_id'][$key],
           'product_name'=>$data['product_name'][$key],
           'product_price'=>$data['product_price'][$key],
           'featured_id'=>$data['featured_id'] // assuming this are the same for all rows?
        ));
    endforeach;
endif; 
}

答案 1 :(得分:0)

执行类似的操作,您可能需要相应地进行一些更改:

function save_featured_product_info($data){
    if( isset( $data['product_id'] ) && is_array( $data['product_id'] ) ){
        foreach( $data['product_id'] as $key => $each ){
            $temp[] = array(
                        'featured_id'  =>$data['featured_id'][$key],
                        'product_id'   =>$data['product_id'][$key],
                        'product_name' =>$data['product_name'][$key],
                        'product_price'=>$data['product_price'][$key],
                      );
        }
        if( isset( $temp ) ){
            $this->db->insert_batch('tbl_featured_products', $temp);
        }
    }
}

答案 2 :(得分:0)

您正在尝试保存数组,您需要内爆值或循环并单独保存或批量插入

$this->db->insert_batch('your_table', $temp);