How would I be able to append data to an array from a form?
A list is generated according to the data found in the database. Each row has a part number and a QTY text field for the user to edit:
+--------+----------+
| Part # | QTY |
+--------+----------+
| 123 | [0] |
+--------+----------+
| 124 | [2] |
+--------+----------+
| 125 | [15] |
+--------+----------+
| | [Submit] |
+--------+----------+
The logic I have so far is:
If QTY = 0 {
ignore
} else {
append values to array object and store array under "parts" session
}
An issue I'm running into is when the form is submitted, it grabs the last part and qty value in the form. I need to somehow make each row unique for the form and input that form data into array.
I plan on after the user adds all the parts and qtys to the array, the array is then submitted into a database.
Is there an easier way of doing this?
Grabs the part number and submits the qty value via the form.
<input type="text" name="item['.$row['Part'].'][qty]" size="2" value="0"/>
So it would look like this:
123 => 0, 124 => 2, 125 => 15
And if value in form is set, map the array. I also used the array_filter()
function to get rid of the 0 qty parts:
function show_Names($e)
{
return "$e[qty]";
}
if(isset($_POST['item'])) {
$c = array_filter(array_map("show_Names", $_POST['item']));
}
And stored it in a session this way. If nothing is set so far, set a new session. If something is set, then just add onto the array:
if(isset($_SESSION['parts'])) {
if(isset($c)) {
$_SESSION['parts']=$_SESSION['parts']+$c;
}
} else {
if(isset($c)) {
$_SESSION['parts']=$c;
}
}
Hope this helps anyone else tackling a similar issue.
Yes. By naming the fields like:
<input type="text" name="item[0][name]" />
<input type="text" name="item[0][email]" />
<input type="text" name="item[1][name]" />
<input type="text" name="item[1][email]" />
<input type="text" name="item[2][name]" />
<input type="text" name="item[2][email]" />
And php script:
function show_Names($e)
{
return "The name is $e[name] and email is $e[email], thank you";
}
$c = array_map("show_Names", $_POST['item']);
print_r($c);
Add square brackets to your textbox name attribute for example:
<input type="text" name="part[]" />
<input type="text" name="qty[]" />
<input type="text" name="part[]" />
<input type="text" name="qty[]" />
<input type="text" name="part[]" />
<input type="text" name="qty[]" />
You will then have all part no & qty into $_POST['part'] and $_POST['qty']