unknown input name check - php

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.

Related

Taking user input and inserting it into an associative array using PHP

I need to put user input into an associative array. The program asks the user how many people are in their group. Then it asks each person's name along with their order. It then proceeds to print out the group member's names along with their orders. My idea was to use a for loop to add each data set into the array. I think I have it all figured out except how to put the data into the array. Here is my code so far:
<?php
$people=readline("How many orders?");
$orders=[];
for($i=0; $i<$people; $i++)
{
print("Order ");
print($i);
print(" name: ");
$name=readline();
print("Order ");
print($i);
print(" order: ");
$food=readline();
}
print("Total order:\n");
foreach($orders as $names=>$orders)
{
print($names);
print(": ");
print($orders);
print("\n");
}
?>
PHP has some of the best documentation of any programming language, so I would advise taking a peak at the array intro, which will show you exactly what you need to know.
As a tip, because you're going to be keeping track of multiple datums per order (name, food), and you will want to be able to associate these with each other later, you will be adding arrays to your $orders array. For example:
$orders[$i] = [$name, $food];
This can be accessed later using numeric indexing:
$orders[$i][0] // value of $name for order $i
$orders[$i][1] // value of $food for order $i
But, in this case, I would actually advise taking the next step and using associative arrays instead:
$orders[$i] = ['name' => $name, 'food' => $food]
This makes access much easier to remember and read:
$orders[$i]['name'] // value of $name for order $i
$orders[$i]['food'] // value of $food for order $i

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

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

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

Categories