View Full Version : php array

02-11-2010, 02:23 PM
I have the following HTML....

<td><input name="qty[1]" onchange="showNextLine(this);" /></td>
<td><input name="ing[1]" onchange="showNextLine(this);" /></td>

and I would like to display the contents so I am using

print $_POST['qty[1]'];

but nothing gets shown?

I am obvouisly not understanding something?

Kind regards


02-11-2010, 02:28 PM

02-11-2010, 02:46 PM
I just tried $_POST['qty'][1]. and it displayed 1 not the contents that were typed into the field?


02-11-2010, 03:00 PM
Sorted that. I didn't realise that things are case sensitive as I was mixing up qty and QTY

Perhaps I could ask you for some more help....

As you saw in my post I have 2 fields qty[1] & ing[1]

I could have up to qty[10] & ing[10] (10 sets of <input> tags.)

What I need to do as add these into a mysql table using PHP using a foreach loop?

my table consists of


some like this????

how would I pass both $_POST ing & qty? I seem to be in a bit of a mess with this below? Any ideas?

foreach ($_POST['ing'] as $key => $value) //This would equate to name="ingredients['.$count++.']" or similar in your form.
mysql_query('INSERT INTO ingredients (parent_id, ingredient) VALUES ('.$parent_id.', '.$value.')') or exit([error message here]);

02-11-2010, 03:14 PM
The easiest way would be to reverse you're array handling in you're input:

<input type="text" name="entry[1]['qty']" />
<input type="text" name="entry[1]['ing']" />
<input type="text" name="entry[2]['qty']" />
<input type="text" name="entry[2]['ing']" />

Then, with php:

foreach ($_POST['entry'] AS $aQtyIng)
list($ing, $qty) = $aQtyIng;
// At this point, $ing and $qty should exist collectively for each entry
// Go ahead and process from this point

Not 100% sure if that will work (not somewhere I can test), but it seems to work out alright in my head lol. With the above, I'd try to just print out the sql before actually making the insertions just to be 100% sure you get the data expected. Also, you can shorten you're SQL by asking for multiple inputs on a single command:

INSERT INTO table (col, col) VALUES
(val1, val2),
(val1, val2),

Same logic could apply to what you have, start the string outside of the loop, append to it inside and call you're query only once.