Ratana
Ratana

Reputation: 9

Insert multiple rows into table

I get a problem with inserting data into database. I use an adding button to add new textbox, default value of first textbox is 10, once clicking on adding button then next textbox will adding value consequency such as 20, 30,.... each textbox have own value. and its individual textbox value send to the same table in one time with a submit button. here code:

//insert into database-Line Item Data
$itemlist = '';
$more = TRUE;
$i=1;
while ($more) {
    if (isset($_POST['lineitem_'.$i])) {
        $itemlist .= $_POST['lineitem_'.$i];
        $itemlist .= "<br />";
    } else {
        $more = FALSE;
    }
    $i++;
}
$query_line_item = "INSERT INTO tbl_order_item (item) values ('$itemlist')";
$result_line_item = mysqli_query($con, $query_line_item);

Code send only first textbox value is 10, for other textbox value don't send.

Upvotes: 0

Views: 93

Answers (2)

Amit Ray
Amit Ray

Reputation: 3485

I prefer this to be saved in an array and then stored in database using serialize. When you want to retrieve you can unserialize it and use it.

$itemlist = array();
$more = TRUE;
$i=1;
while($more)
{
    if (isset($_POST['lineitem_'.$i]))
    {
        $itemlist[]= $_POST['lineitem_'.$i];
    }else
    {
        $more = FALSE;
    }
$i++;
}
$itemlist = serialize($itemlist);//serialize to store an array in database
$query_line_item = "INSERT INTO tbl_order_item (item) values ('$itemlist')";
$result_line_item = mysqli_query($con, $query_line_item);

When you want to retrieve it and use it just use

$itemlist = unserialize($itemlist);//unserialize to use as an array

EDIT as per your latest code: $add_nr is defined somewhere in this code I suppose

    $line_item = ''; 
     $more = TRUE; 
    for ($i=0; $i<5; $i++) 
    { 
    if((isset($_POST['lineitem_'.$i])) && ($_POST['lineitem_'.$i] !="") && isset($_POST['materialcode_'.$i]) && isset($add_nr))
    { 
    $line_item = $_POST['lineitem_'.$i]; 
    $materialcode = $_POST['materialcode_'.$i]; 
    $query_line_item = "INSERT INTO tbl_order_item (order_number, item, material) 
values ('$add_nr', '$line_item', '$materialcode')"; $result_line_item = mysqli_query($con, $query_line_item); 
    }else { 
    $more = FALSE; 
    } 
    }

Upvotes: 0

Kalrav Joshi
Kalrav Joshi

Reputation: 86

You must use textbox name array to get values of all text boxes, to do so put this name (name="lineitem[]") in all textboxes you generate and you will get an array of values when you submit data, then in php script use foreach loop to cycle through array and also run that insert query in that foreach loop that way you will get all the values of textboxes in the table at the same time.

Use this link for reference:

https://www.sanwebe.com/2013/04/capture-array-values-from-dynamic-input-fields-using-php

Upvotes: 2

Related Questions