如何在Codeigniter中插入动态数据? [英] How to insert dynamic data in Codeigniter?

查看:120
本文介绍了如何在Codeigniter中插入动态数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想将动态生成的输入字段数据插入数据库.我的数据库表具有三个字段 id(自动递增),product_name和rate .我正在尝试使用动态生成的输入字段将批量数据插入数据库中,在这里我可以手动添加/删除输入字段. 我将输入字段创建为

I just want to insert dynamic generated input field data into database . My db table having three fields , id(Auto Increment), product_name and rate . I'm trying to insert bulk data into database using dynamically generated input fields where I can add/remove input fields manually. I created the input fields as

<input class="form-control" placeholder="Product Name" name="prodname[]" type="text">
<input class="form-control" placeholder="Product Rate" name="prodrate[]" type="text">

这是我的下面的控制器

function Act_AddProducts() {
        if ( $this->input->post( 'prodname' )&&$this->input->post( 'prodrate' )) {
            foreach ( $this->input->post( 'prodname' ) as $key => $value ) {

                $this->ProductModel->add_products( $value );
            }

        }

模型功能在下面

function add_products($val)
  {
      if($this->db->insert('tbl_product_master', array('product_name' => $val)))
      {
        return true;
      }
      else
      {
        return false;
      }
  }

现在,该值一次插入db中.因此,请帮助我确定代码问题.另外,我不太了解如何将 prodrate [] 值插入同一插入查询.

Now the value is inserting into db but one at a time. So please help me to identify the issue with code. Also I don't really understand how to insert prodrate[] value into the same insert query.

推荐答案

希望这对您有帮助

您的控制器Act_AddProducts应该是这样的:

Your controller Act_AddProducts should be like this :

function Act_AddProducts() 
{
   $prodnames = $this->input->post( 'prodname' );
   $prodrates = $this->input->post( 'rate' );
    if ( ! empty($prodnames) && ! empty($prodrates) ) 
    {
        foreach ($prodnames as $key => $value ) 
        {
            $data['product_name'] = $value;
            /* make sure product_rate columns is correct i just guess it*/
            $data['product_rate'] = $prodrates[$key];
            $this->ProductModel->add_products($data);
        }

    } 
}

您的模型add_products应该是这样的:

Your model add_products should be like this :

function add_products($data)
{
   if ( ! empty($data))
   {
      $this->db->insert('tbl_product_master', $data);
   }
}

这篇关于如何在Codeigniter中插入动态数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆