PHP - Get input from dynamically added html table rows - php

I have the following Fiddle set up here Fiddle
As you can see, I am able to add inputs by clicking the Add Row button.
All inputs that are added have a unique id and name. The problem is, I cant just do something like
$actionInput = $_POST["actionInput"];
Because I might need
$actionInput1 = $_POST["actionInput1"];
$actionInput2 = $_POST["actionInput2"];
$actionInput3 = $_POST["actionInput3"];
Depending on how many rows are added. So how can I get all the inputs without knowing what inputs I need to grab?
Thanks

Actually, you need to maintain counter in hidden, which you will get at the time of posting the form in case you don't want to maintain elements as array, otherwise you can put elements as array as described below:
<input type=text name="inputs[]" />

Name your inputs with array boundary, like:
<input type=text name="actioninput[]" />
now you can itreate throught them in you POST or GET ( depends ) array:
print_r($_POST);

Assuming your JSFiddle works fine for you, following are the steps.
1) Get keys of $_POST.
2) Get maximum counter value from keys.
3) Take a for loop from 0 to count of post.
4) If counter is 0, no suffix, else, add counter as suffix.
5) Now, you get posted variable.
6) Repeat it for every element in rows.
<?php
$keys = array_keys($_POST);
$keys = implode(',', $keys);
$n = str_replace('actionInput', '', $keys);
$m = explode(',', $n);
$max = max($m);
for ($i=0 ; $i<=$max ; $i++) {
$suffix = ($i==0) ? '' : $i;
if (isset($_POST['actionInput' . $suffix])) {
echo "<br/>-".$_POST['actionInput' . $suffix];
}
}

replace name=actionInput with name=actionInput[]
it should be an array with same name
same thing will apply with all form fields generated dynamically whose values you'll need.

Change this line in Add row jquery event
return name + i to return name
Remove i from it and then
name=actionInput[]
print_r($_POST);
It will gives array of actioninput

Related

How to delete last value in foreach loop

I have a dynamic multi input. When submit form, inserting array values. But I want to insert without 'submit' value.
This is the foreach loop, (sql secure not included)
if (isset($_POST['submit'])) {
$nearest = $db->prepare('insert into nearest set place=?, distance=?');
$i = 0;
foreach ($_POST as $val) {
$place = $_POST['place'][$i];
$distance = $_POST['distance'][$i];
$nearest->execute([$place, $distance]);
$i++;
}
}
This loop inserted '$_POST' values and inserted empty row.
If you want to keep the loop you can use array_slice to not include the last item in the loop.
Array_slice will take items from 0 (not literal, but the first item) to second to last (-1).
http://php.net/manual/en/function.array-slice.php
EDIT; I think you need a for loop to loop the count of "place".
if (isset($_POST['submit'])) {
$nearest= $db -> prepare('insert into nearest set place=?, distance=?');
for($i=0; $i< count($_POST['place']; $i++){
$place = $_POST['place'][$i];
$distance= $_POST['distance'][$i];
$nearest-> execute([$place , $distance]);
$i++;
}
}
example: https://3v4l.org/F47ui
You can simply remove your submit key from $_POST prior doing your loop with just regular unset(). But this is bad approach. What I'd rather recommend doing instead is to "isolate" your data, and instead of this:
<input name="distance" ... >
make all your imputs like this:
<input name="data[distance]" ... >
then you just need to loop over "data" (name as you like) array:
foreach($_POST['data'] as val)
Also, resist from removing last element in blind, because it's based on false assumption that this is always your "submit" element. What if you add more submit buttons to the form? or the order will change?

access via post method input with integer name

If I have a form that contains many fields generated dynamically (their names are integer, because they are named after the iteration that generates them). I need to get their values via post or get (this is an issue i will deal with myself, so lets assume its post).
the code for the inputs:
for ($x = 0; $x < 5; $x++)
for ($y = 0; $y < 12; $y++){
echo '<input type="text" name="'.$x.'"> Bar 1<br/>';
}
How can i get all the 12th values in an array on the server side using php? I generally know how to use post, but in this case what should i put inside the brackets of $_POST[]?
And what is the correct syntax to make the name an array?
Go through the post and ever 12th pull out a value just add a counter. If other posted information is in form, then do a preg match for first part of your key name and then iterate over counter on that name.
foreach ($_POST as $key => $value)
echo "Field ".htmlspecialchars($key)." is ".htmlspecialchars($value)."<br>";
If that approach isn't appealing, JSON encode the values being sent in an array to the php then do a json_decode into a php array and then take out every twelfth element.
Your code will produce twelve input fields with the same name ($x), which wont work (each input needs a unique name).
If I remember correctly, you can do something like this:
echo '<input type="text" name="'.$x.'[]"> Bar 1<br/>';
and it will generate an array in $_POST: $_POST[$x][0] = 'first', $_POST[$x][1] = 'second', ...

Post HTML elements array to PHP

Here is the snapshoot of my form. The input values under LPO (1st column) are hidden, I just showed them here to show complete form.
if color_id (first left most inputbox) is 37 its DB value is BB552 as displayed. And if its 3, the value of that color is BB110, but when its 0, it means a user has selected Custom and written a value by him self in the third row it is FFBBBAA.
I need to submit the form to PHP
The field names are as follows
color_id[] <-- Hidden input
order_id[] <-- Hidden input
subcolor_id[] <-- Select
subcolor_string[] <-- Input
material_id[] <-- Select
weight[] <-- input
When I post the form, in PHP
<?PHP
$count = count($_POST['weight']);
for($i = 0; $i < $count; $i++){
$color_id = $_POST['color_id'][$i];
$order_id = $_POST['order_id'][$i];
$material_id = $_POST['material_id'][$i];
$weight = $_POST['weight'][$i];
// i can count one post item and can iterate over all.
if($color_id == 0){
$color_id = $_POST['subcolor_id'][$i]; // this give me wrong result;
}
}
So when 0 is there, admin approving this form, can leave it to custom or change the color back to some value from DB
I want to know what are the possibilities for getting the proper sub color values if first hidden input color_id has 0.
So far the one which I thought of is to add two more hidden fields in Sub Color columns to match their index, but this will require me to completely re-write the del sub color code
Is there any other way which can save me from doing lots of alterations to this form?
as eds mentioned it totally makes sense.. u shud do this way
$j=0;
$count = count($_POST['weight']);
for($i = 0; $i < $count; $i++){
$color_id = $_POST['color_id'][$i];
$order_id = $_POST['order_id'][$i];
$material_id = $_POST['material_id'][$i];
$weight = $_POST['weight'][$i];
// i can count one post item and can iterate over all.
if($color_id == 0){
$color_id = $_POST['subcolor_id'][$j]; // this give me wrong result;
$j++;
}
}
this shud solve your problem..
Your other option is to declare another iterator $j outside of the loop, starting at 0, and manually incrementing that iterator after you read a subcolor each time. Then it should always be the index of the next subcolor_id you need to read.

moving a numbered amount of named items from one array into another

I'm not exactly sure how the logic would work on this. My brain is fried and i cant think clearly.
I am handling some POST data, and one of the fields in this array is a quantity string. I can read this string and determine if there are more than 1 widgets that need handled.
if($quantity <= 1){ //$_POST[widget1] }
Now say there are 4 widgets. The quantity field would reflect this number, but how would i loop through them and assign them to a new array themselves?
$_POST[widget1], $_POST[widget2], $_POST[widget3], $_POST[widget4]
How do i take that quantity number, and use it to grab that many and those specific named items from the post array, using some kind of wild card or prefix or something? I dont know if this is a for, or while, or what kind of operation. How do I loop through $_POST['widget*X*'], where X is my quantity number?
The end result is im looking to have an array structured like this:
$widgets[data1]
$widgets[data2]
$widgets[data3]
$widgets[data4]
Using a for loop, you can access the $_POST keys with a variable, as in $_POST["widget$i"]
$widgets = array();
for ($i=1; $i<=$quantity; $i++) {
// Append onto an array
$widgets[] = $_POST["widget$i"];
}
However, a better long-term solution would be to change the HTML form such that it passes an array back to PHP in the first place by adding [] to the form input's name attribute:
<input type='text' name='widgets[]' id='widget1' value='widget1' />
<input type='text' name='widgets[]' id='widget2' value='widget2' />
<input type='text' name='widgets[]' id='widget3' value='widget3' />
Accessed in PHP via $_POST['widgets'], already an array!
var_dump($_POST['widgets']);
Iterate over the number of items, at least over one (as you describe it):
$widgets = array();
foreach (range(1, max(1, $quantity)) as $item)
{
$name = sprintf('widget%d', $item);
$data = sprintf('data%d', $item);
$widget = $_POST[$name];
// do whatever you need to do with that $widget.
$widgets[$data] = $widget;
}

Count amount of similar items in array, return value if under 3

I have an array which contains sets of three similar named items; however, sometimes there's only two items in a set and I want to call these out.
<?php
$items = array(
'reviewpitfighter-1.138x88.jpg',
'reviewpitfighter-2.138x88.jpg',
'reviewpopfulmailsegacd-1.138x92.jpg',
'reviewpopfulmailsegacd-2.138x76.jpg',
'reviewpopfulmailsegacd-3.138x97.jpg'
);
?>
You'll note that there are two reviewpitfigher* items, and three reviewpopfulmailsegacd* items. I've started down a rabbit hole of loops and feel that there is something simple I'm just glossing over.
May be you can do this as a 2 stage process.
Stage 1:
Loop through the original array and form another set of array with its key as the value of this original array. Then save the repetition count in each of those new arrays.
Stage 2:
Loop through the new set of arrays and then pick out the arrays which has values less than 3 and retrieve its key.
Hope this helps!!
Here's the solution I came up with, sorry it took so long to post.
foreach($images as $value){
$lastItem = explode('-', $images[$count - 1]);
$parts = explode('-', $value);
if(preg_match('/^1/', $parts[1]) && $count != 0){
if(preg_match('/^2/',$lastItem[1])){
$imgurl = preg_replace('/^p?review/','',$lastItem[0]);
$sql = 'SELECT field FROM table WHERE field = "' . $imgurl . '"';
$result = $dbConn->FetchArray($dbConn->Query($sql), MYSQL_ASSOC);
$array[$imgurl] = $result;
}
}
$count++;
}
I get an array of all the images, then I check to see if I'm looking at the first image, if I am then I see if the last image I looked at was the second image. At this point I then call into the database to get some information to display a neatly messaged out put of what reviews are missing a third image. In the end $array contains this list which I can loop over.

Categories