Looping through POST variable array

I have a html form with a table with a dynamic row and a button that adds a new row when pressed.
Each row has the input fields, each with an array name.

Ref[], id[], name[], price[], quantity[]

When I submit the form I want to take each row of the table and write it out as a record to a sql server table.

I am ok with the sql code but as a php newbie I am struggling working out how to loop through the rows of POST variables

Any suggestion would be much appreciated

You can send 2D arrays over HTTP POST. You can see how this is done in the example below:

        <form method="post">
            <input name="people[0][name]" type="text">
            <input name="people[0][age]" type="text">
            <input name="people[1][name]" type="text">
            <input name="people[1][age]" type="text">
            <input type="submit">

You can use your “add row” button to add another pair of inputs with increasing indexes, so the next pair would be:

            <input name="people[2][name]" type="text">
            <input name="people[2][age]" type="text">

If you submit the form above, you’ll get something like the following in $_POST:

    [people] => Array
            [0] => Array
                    [name] => Alice
                    [age] => 32
            [1] => Array
                    [name] => Ben
                    [age] => 48

Many thanks Skawid. If I read your suggestion correctly I should then change my naming to a common pre bit such as ITEM[ ].Ref, ITEM[ ].ID etc them I can get the count of ITEM[ ] as a loop limiter and pull each individual row off and add it to the table

You don’t need to count the array in PHP, just use foreach:

foreach ($_POST['people'] as $person) {

Even better, many thanks again

Actually, just one further question if you have the patience

For each People as $person

Does this give me the entire row and from there I need to separate the individual keys, and if so what I’d the syntax for thst

Try it, see what you get. :slight_smile:

for each ($_POST['people'] as $person) {

var_dump will print a variable out. It’s good for examining the structure of a variable if you’re not sure what you’re working with.

Thanks Skawid. I haven’t forgotten your suggestion, it’s just thst I had to go into hospital suddenly anc haven’t had chance to do further work

I am just out now and will be back at the console tomorrow, so, for now, many thanks

Sorry, I am struggling with the syntax, or posible I jus don’t unerstand it.

Here is my input line

<tr class="timesheet-row" >
											<td style="text-align:center; width: 8%" >
											      <input type="text" name="item[ref]" style="width:95%"  required value="<?php echo $_POST['ItemRef'] ?>" >
											<td style="text-align:center; width: 28%">
											      <input style="width:95%" type="text" name="item[][des]"  required value="<?php echo $_POST['ItemDescription'] ?>" >
											<td style="text-align:center; width: 10%" >
											      <input style="width:95%" type="text"  name="item[][cc]"  required value="<?php echo $_POST['ItemCC'] ?>" >
											<td style="text-align:center; width: 10%" >
											      <input style="width:95%" type="text" name="item[][val]" value="<?php echo $_POST['ItemValue'] ?>" >
											<td style="text-align:center; width: 10%">
											      <input style="width:95%" type="number" step="0.10" name="item[][weight]" required value="<?php echo $_POST['ItemWeight'] ?>" >
											<td style="text-align:center; width: 10%">
											      <input style="width:95%" type="text" name="item[][origin]" value="<?php echo $_POST['ItemCofO'] ?>" >
											<td style="text-align:center; width: 8%">
											      <input style="width:95%" type="text" name="item[][poid]" value="<?php echo $_POST['PurchaseOrder'] ?>" >
											<td style="text-align:center; width: 8%">
											      <input style="width:95%" type="text" name="item[][quantity]" value="<?php echo $_POST['QuantityofItems'] ?>"  >

Now, when I hit submit I ned to loop through an unknow number of these lines and for each line create a SQL Server table row.

What I have tried but fialed to do if reference each of the column names individually.
I have tried item[]REF, item[][ref], item[ref] but nothing workls. I clearly have failed this mission!!!

For some reason it won’t show the formatted txt but here is the gist of it
<input type=“text” name="item[ref]
<input type=“text” name="item[des]
<input type=“text” name="item[cc]
<input type=“text” name="item[val]

To post code, use either bbcode [code][/code] tags, on their own lines before/after your code or three mark-down back-ticks ```, on their own lines before/after your code. I have edited your post above to add bbcode tags.

The method that @skawid showed requires that you give the array elements for each field within a set the same numerical value, both when you (re)display the form and when you dynamically add a row in the browser. You cannot use [] in that leading position since it will result in a separate array entry for every field in the form.

You can see what the submitted data looks like using -

echo '<pre>'; print_r($_POST); echo '</pre>';

I recommend that you put the [] on the end of each field name, then to loop over the item data, loop over the item array keys from one of the fields, e.g. ‘ref’, and access the values from each same row of submitted data.

foreach(array_keys($_POST['item']['ref']) as $key)
	// use $key here to access each same row field value...
	// e.g. the 'ref' value -
	echo $_POST['item']['ref'][$key];

Thanks @phdr; so use the $key as a row number and then just change the sub-field name with the static $key value to collect all the individual row field values?

You could do that, but you would be typing out lines of code for every field, repeated each time you do something new. Instead, since you will be operating on each element of data in the similar/same way, use a data-driven design, where you have a data structure (array, db table) that defines the expected fields, then loop over this defining structure to dynamically access each element in the data.

// define the expected item fields
$item_fields = ['ref','des','cc','val','weight','origin','poid','quantity'];
Sponsor our Newsletter | Privacy Policy | Terms of Service