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">
This is my controller below
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 );
}
}
Model function is below
function add_products($val)
{
if($this->db->insert('tbl_product_master', array('product_name' => $val)))
{
return true;
}
else
{
return false;
}
}
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.
Hope this will help you
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);
}
}
}
Your model add_products
should be like this :
function add_products($data)
{
if ( ! empty($data))
{
$this->db->insert('tbl_product_master', $data);
}
}