[英]Saving multiple checkbox data by foreach in MySQL using 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);
}
请让我知道您身边的解决方案。 谢谢
您的问题是输入$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;
}
做这样的事情,您可能需要相应地进行一些更改:
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);
}
}
}
您正在尝试保存数组,您需要内插值或循环并单独保存它们或批量插入它们
$this->db->insert_batch('your_table', $temp);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.