access via post method input with integer name - php

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', ...

Related

PHP - Get input from dynamically added html table rows

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

Dynamic form and looping through form array to insert into Mysql

I have a form that is built dynamically:
foreach($xml->config->popup as $popup_item){
<input class="fm-req" id="fm-popup_name[]" name="fm-popup_name[]" type="text" value="" />
<textarea class="fm-req" rows="4" cols="50" id="fm-popup_desc[]" name="fm-popup_desc[]" /></textarea>
<input class="fm-req" id="fm-popup_image[]" name="fm-popup_image[]" type="file" />
}
I haven't worked with arrays in form names before but i seen on another post on stack overflow you could do this and it seems like this is a much better way than i had planned, which was to add $i to the end of the name and increment each loop so i would have ended up with:
fm-popup_name1
fm-popup_name2
fm-popup_name3 etc etc
I could then do a loop count when building the form, pass the count as a hidden field and then use a for loop where x <= count and do my insert that way. But in the interest of improving the code and keeping it more compact and easy to understand, i think its worth doing this way but i cant figure out a good way to do it:
foreach($_POST['fm-popup_name'] as $index => $value) {
// get the value of name
}
foreach($_POST['fm-popup_desc'] as $index => $value) {
// get the value of name
}
foreach($_POST['fm-popup_image'] as $index => $value) {
// get the value of name
}
With that i can access all the data i need but i don't want to make 3 separate inserts for 1 record.
How can i take the information above and something like:
foreach($_POST['fm-popup_name,fm-popup_desc,fm-popup_image'] as $index => $value) {
INSERT INTO mytable(
popup_name,
popup_desc,
popup_image
)
VALUES(
'$popup_name',
'$popup_desc'
'$popup_image'
)";
}
Any ideas? Hopefully code is ok, i filtered out all the other crap that is irrelevant so hopefully all the id's etc match but im just looking for a rough example and i can convert back to my code.
You can use something the following, but there is a risk (can you spot it?) :
$entries = count($_POST['fm-popup_name']);
for($i = 0; $i < entries; ++$i) {
$name = $_POST['fm-popup_name'];
$desc = $_POST['fm-popup_desc'];
// other processing
}
If you haven't spotted it, the risk is that not all array elements may be populated, so you may not get a proper mapping for each row, unless you enforce it on the front end and validate this before processing your loop.

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;
}

unknown input name check

How can I check the inputs below:
<?php
for($i = 0; $i < 9; $++){
echo "<input type='text' name='{$i}[qty]'>";
}
?>
now my qustion is how can I check the unknown input name if the value is bigger than 10 or smaller than 1?
You did explain too little about your usage or the rest of your form structure. But generally you don't want to name the fields not with a number first, but the other way around:
print "<input type='text' name='qty[$i]'>";
// would also work with just 'qty[]' in most cases
This way it becomes a very simple indexed array upon receival in PHP which you can traverse with:
$_REQUEST["qty"][$i++]
// or
foreach ($_REQUEST["qty"] as $i => $qty) {
This way you wont miss either larger indexes than 10 or those below 0 - although you really should avoid negative indexes. (Not because it doesn't work, but it's probably an unoptimal methodology.)
If you use these qty form fields of part of another group, then you want to use the same array[$i] naming for all of them. Thus when you foreach over the loop you can access all in groups: $_REQUEST["qty"][$i] belongs to $_REQUEST["product"][$i] for example.

How to process a large post array in PHP where item names are all different and not known in advance?

I have a PHP page that queries a DB to populate a form for the user to modify the data and submit.
The query returns a number of rows which contain 3 items:
ImageID
ImageName
ImageDescription
The PHP page titles each box in the form with a generic name and appends the ImageID to it. Ie:
ImageID_03
ImageName_34
ImageDescription_22
As it's unknown which images are going to have been retrieved from the DB then I can't know in advance what the name of the form entries will be.
The form deals with a large number of entries at the same time.
My backend PHP form processor that gets the data just sees it as one big array:
[imageid_2] => 2
[imagename_2] => _MG_0214
[imageid_10] => 10
[imagename_10] => _MG_0419
[imageid_39] => 39
[imagename_39] => _MG_0420
[imageid_22] => 22
[imagename_22] => Curly Fern
[imagedescription_2] => Wibble
[imagedescription_10] => Wobble
[imagedescription_39] => Fred
[imagedescription_22] => Sally
I've tried to do an array walk on it to split it into 3 arrays which set places but am stuck:
// define empty arrays
$imageidarray = array();
$imagenamearray = array();
$imagedescriptionarray = array();
// our function to call when we walk through the posted items array
function assignvars($entry, $key)
{
if (preg_match("/imageid/i", $key)) {
array_push($imageidarray, $entry);
} elseif (preg_match("/imagename/i", $key)) {
// echo " ImageName: $entry";
} elseif (preg_match("/imagedescription/i", $key)) {
// echo " ImageDescription: $entry";
}
}
array_walk($_POST, 'assignvars');
This fails with the error:
array_push(): First argument should be an array in...
Am I approaching this wrong?
Would it be possible to change the way the items are named on the form?
Current:
ImageID_03
ImageName_34
ImageDescription_22
Changed To:
ImageID[03]
ImageName[34]
ImageDescription[22]
This way it should come through the $_POST as three separate arrays meaning you can skip all that extra processing.
I hate to edit many rows at once. It's usability fault
If I go for it, I'd make it with such a form:
<form method="POST">
<input type="text" name="name[1]">
<input type="text" name="desc[1]">
<input type="text" name="name[2]">
<input type="text" name="desc[2]">
...etc
</form>
So, I'd have 2 arrays, $_POST['name'] and $_POST['desc'] where id used as a key
In your case I wouldn't use array_walk as it's just a syntax sugar, and make it with foreach to have full contorol over data processing.
I think you need
global $imageidarray;
to access a global array inside a function.
Something like this would work as well, assuming your three form fields are always submitted together:
$ids = preg_grep('/^imageid_(\d+)$/', array_keys($_POST)); // $ids now contains only the imageid_* keys
foreach($ids as $id) {
$id = substr($ids, 8); // now contains the numeric id of the field
echo $id, ": ", $_POST["imageid_$id"], "\n";
}
Not as efficient as using the array notation in the form names, but allows you to trivially extract just the ID numbers from one of the field names and then use it to access the other matching fields as well.

Categories