I need help making a PHP form parse code lighter - php

I have a PHP form which allows users to enter up 99 items if they do so desire. I was hoping that PHP doesn't need me to parse each individule item and it can handle doing a loop or something for when there are many items enter.
currently my php looks like this
$item1 = $_POST['Item1'] ;
$item2 = $_POST['Item2'] ;
$item3 = $_POST['Item3'] ;
$item4 = $_POST['Item4'] ;
$item5 = $_POST['Item5'] ;
// etc, etc
But I don't want 99 lines of code if only 5% of people enter more than one item in the form.

Have all the inputs named items[] (note the []). You can then access them all in an array called $_POST['items']. You can then iterate through all the values:
foreach($_POST['items'] as $item)
{
// ...
}

change the input-names like this:
<input type="text" name="items[]"/>
<input type="text" name="items[]"/>
<input type="text" name="items[]"/>
and you'll get an array:
$items = $_POST['items'] ;
foreach($items as $item){
// walk throug items and do something
}

You need to name your input elements like this:
<input type="text" name="Item[]" value="A" />
<input type="text" name="Item[]" value="B" />
<input type="text" name="Item[]" value="C" />
And then in PHP you will see this in $_POST as an
array(
0 => 'A',
1 => 'B',
2 => 'C'
)
This is a standard PHP trick, and you can use it to get any elements automatically inside the same array when reading them from $_POST and $_GET.

Another alternative :
foreach($_POST as $index => $value) {
$item[$index] = $value;
}

for ($i = 1;$i<100;$i++)
{
${"item".$i} = $_POST['Item'.$i];
}
//or you can use variables directly
//echo ($_POST['Item1']);
or you can change Item1, Item2, .... in form to Items[] and then call it like
$items = $_POST['Items'];
print_r($items);
/*
array
(
[0] => "some"
[1] => "text"
[2] => "another"
[3] => "text"
)
*/

foreach ($_POST as $key=>$value) {
if (substr($key, 0, 4)=="Item") {
$item[substr($key, 4)]=$value;
}
}

Related

PHP Form keep input values together to create JSON list

I have a JSON list with conditions(items) and a color associated to every condition. I'm building a form to try to update the conditions, then return to the JSON format.
Example:
<?php
?>
$JSON_list = {
"FULL":"green",
"Half-Full":"amber",
"Quarter-Full":"amber",
"Empty":"red"
}
I json_decode() this list to turn it into a php array. Then iterate through it and display the values as inputs which can be edited.
<form action="updatedata.php" method="post">
<?php
foreach($JSON_list as $condition) {
foreach($condition as $item => $color){
?>
<input type="text" name="item[]" value="<?=$item;?>">
<select name="color[]">
<option selected="selected"><?=$color;?></option>
<option>green</option>
<option>amber</option>
<option>red</option>
</select>
<br>
<?php
};
};
};
?>
<input type="submit" value="Submit Conditions">
</form>
On submission of the form, the "items" & "colors" are stored in 2 different arrays separate from each other. I iterate through each of these arrays to obtain the new values, and then concatenate them into a JSON list again.
updatedata.php:
<?php
$num = count($_POST['item']);
$i = 1;
$subs = [];
foreach($_POST["item"] as $item){
$subs["item".$i] = $item;
$i++;
};
$c = 1;
foreach($_POST["color"] as $item){
$subs["color".$c] = $item;
$c++;
};
$submit_string = "";
$a = 1;
$comma = ",";
for($x = 0; $x < $num; $x++){
if($a == $num){
$comma = "";
};
$submit_string .= "\"".$subs["item".$a]."\":"."\"".$subs["color".$a]."\"".$comma;
$a++;
};
echo "{" . $submit_string . "}";
//Prints the JSON string "FULL":"green","Half-Full":"amber","Quarter-Full":"amber","Empty":"red"
?>
My problem occurs when the "item" input is submitted with nothing, if an item has a value of "" then I don't want this entry in the JSON list. I need to delete this entry, but also the "color" associated to that item.
Is there a way to link the "items" & "numbers" from the form so I can delete both entries??
I think there is maybe a bit more to your code you are not showing us, for example with the given structure of $JSON_list the 2 nested foreach loops you have to generate the HTML would not work. Here's what I did to get your code working:
$JSON_list needs quotes and a trailing semi-colon:
$JSON_list = '{
"FULL":"green",
"Half-Full":"amber",
"Quarter-Full":"amber",
"Empty":"red"
}';
Convert it to an array:
$array = json_decode($JSON_list, true);
Generate the HTML:
<?php foreach ($array as $item => $color) { ?>
<input type="text" name="item[]" value="<?php echo $item; ?>">
<select name="color[]">
<option selected="selected"><?php echo $color; ?></option>
<option>green</option>
<option>amber</option>
<option>red</option>
</select>
<br>
<?php } ?>
Next, if you dump out what you're getting back from a form submission, it gives you an idea of how to process it. Here's the output of print_r($_POST); after the form was submitted with the "HALF-FULL" text input blank:
Array
(
[item] => Array
(
[0] => FULL
[1] =>
[2] => Quarter-Full
[3] => Empty
)
[color] => Array
(
[0] => green
[1] => amber
[2] => amber
[3] => red
)
)
So now the relation between the 2 arrays is clear, and you can see we can use the array keys to map the elements of one to the other.
// We'll store our results in this new array
$submitted = [];
// Iterate over the first array elements
foreach ($_POST['item'] as $key => $value) {
// We only want to include item/colors that were non-blank,
// so check if we got an item here
if ($value) {
// OK it wasn't blank, so let's save the result, using
// the corresponding element from the color array
$submitted[$value] = $_POST['color'][$key];
}
}
// Now we have an array of our submitted data
// print_r($submitted);
// Array
// (
// [FULL] => green
// [Quarter-Full] => amber
// [Empty] => red
// )
// You should never try to construct a JSON string manually, just
// let PHP do it for you:
$newList = json_encode($submitted);
// echo $newList;
// {"FULL":"green","Quarter-Full":"amber","Empty":"red"}

Add values and keys to session and store each individual addition (php)

I am at my wits end for last three days.
What i want to do is to code shopping-cart like functionality. So, i have two inputs that i want EACH to store in its own array.
something along the lines of:
<?php
session_start();
$input1 = [];
$input2 = [];
if(isset($_POST['submit']))
{
$input1 = $_POST['first'];
$input2 = $_POST['second'];
$_SESSION['test'] = [
'first' => array_push($input1),
'second' => array_push($input2)
];
}
var_dump($_SESSION['test']);
?>
and my html is as follows :
<form method="post">
<input type="text" name="first" value="">
<input type="text" name="second" value="">
<input type="submit" name="submit" value="array">
</form>
Now i expect the output of var_dump to be as follows:
Array(
[First] => ('Random1','Random2')
[Second] => ('Flower1','Flower2')
)
But what i get in the best case is:
Array(
[First] => Random1
[Second] => Flower1
[0] => Random2
[1] => Flower2
)
So, my question is 1) How can i add values to $_SESSION['test'] as an array
and 2) How can i store each input in it's corresponding array?
array_push takes at least two parameters: an array, and something to push into it. You're giving it the one input, and then are not pushing anything into it. Further, you're replacing your entire $_SESSION['test'] on every run, overwriting it with new (nonsense) values.
What you want is:
$_SESSION['test']['first'][] = $input1;
$_SESSION['test']['second'][] = $input2;
Append something to the end of the existing arrays, not overwrite them.

update multidimensional array

I have a multidimensional array containing character names from the Simpsons (homver, Marge and bart) and I have echoed the keys and values in a foreach loop. I want to have two input boxes next to each character name, that updates the id and size of each specific name.
I have the code bellow. The values are showing inside the input box but they are not updating :(
Thanks in advance for all the help
CODE
//
<?php
session_start();
$array=array(
'Homer' => Array
(
'id' => 111,
'size' => 54
),
'Marge' => Array
(
'id' => 222,
'size' => 12
),
'Bart' => Array
(
'id' => 333,
'size' => 3
)
);
////////////////////////////////////
if (isset($_POST["submit"])) {
for ($i = 0; $i < count($_POST['names']); $i++) {
$names = $_POST['names'][$i];
$ids = $_POST['ids'][$i];
$sizes = $_POST['sizes'][$i];
}
}
////////////////////////////////////
echo "<form method='post' action=''>";
// put the array in a session variable
if(!isset($_SESSION['simpsons']))
$_SESSION['simpsons']=$array;
// getting each array in a foreach loop
foreach( $_SESSION['simpsons'] as $character => $info) {
echo $character.': id is '.$info['id'].', size is '.$info['size'];
//add and update input box for each ' id ' and ' size '
?>
<input type="text" name="names[]" value="<?php echo $character;?>" />
<input type="text" name="ids[]" value="<?php echo $info['id'];?>" />
<input type="text" name="sizes[]" value="<?php echo $info['size'];?>" />
<?php
echo"<br/>";
}
?>
<!-- submit button for the form -->
<input class="inputbox" type="submit" value="Update value of key" name="submit"/>
</form>
The Issue
Let's take a look at what your code does when a user submits the form...
if (isset($_POST["submit"])) {
for ($i = 0; $i < count($_POST['names']); $i++) {
$names = $_POST['names'][$i];
$ids = $_POST['ids'][$i];
$sizes = $_POST['sizes'][$i];
}
}
Great. You take the form data, and loop through each character in your simpsons array, and for each character set $names,$ids, and $sizes.
There are two issues that I see.
The three variables you set that I named above, are not arrays, but hold single values for the specific character at that iteration in the loop.
Nothing is done with the variables. The values are set for one character, and then overwritten for the next. Nothing is done with the data.
One Possible Solution
So let's do something with the data from the form. Here is my solution.
if (isset($_POST["submit"])) {
$newArray = [];
for ($i = 0; $i < count($_POST['names']); $i++) {
$newArray[$_POST['names'][$i]] = [
'id' => $_POST['ids'][$i],
'size' => $_POST['sizes'][$i]
];
}
$_SESSION['simpsons'] = $newArray;
}
If the form is submitted, we make a new temporary array. We then add new sub arrays for each character with their set id and size. Then we put that array into the session.

Sending html array to a PHP form

This is my actual code. I am trying to send the array "sku" which has copied the original array of "parent..." to php with $_post. But no matter what I try it won't send.
<script>
var sku = new Array();
for (q=1;q<parent.item_num;q++)
{
sku[q] = parent.itemlist[q].code;
}
</script>
Please help.
If the name attribute is something like name="item[]", then $_POST['item'] is an array, so you can use foreach loop to go through all items.
If your form method is post you can use <?php $_POST['item'] ?> to access the array.
You can also use foreach to loop through all of the items:
<?php
foreach($_POST['item'] as $item){
... do something with $item ...
}
?>
Arrays in HTML, e.g.
<input type="text" name="arr[]" id="arr1" />
<input type="text" name="arr[]" id="arr2" />
simply create arrays under their normal $_GET/$_POST variables, so, var_dump($_REQUEST['arr']) would yield:
arr => array(
[0] => "whatever was in arr1",
[1] => "whatever was in arr2"
)
maybe this will help :
$id = 4;
if (isset($_POST['item_'.$id]))
{
item[$id] = $_POST['item_'.$id];
} else {
item[$id] = 0;
}
PS : slugonamission way seems more appropriate

Count posts with iterator

can i count how many POST's are submitted as Field_Amount_1, Field_Amount_2, Field_Amount_3, etc... like this ?
$Counting = count($_POST['Field_Amount_']);
Thanks for any suggestion
Well the easiest way would be to correct your form like:
<input name="Field_Amount[]" type="text" />
<input name="Field_Amount[]" type="text" />
<input name="Field_Amount[]" type="text" />
This makes it post an array so $_POST would contain:
Array (
'Field_Amount' => Array (
0 => 'amount'
1 => 'amount'
2 => 'amount'
)
)
Then you can just do count($_POST['Field_Amount'])
The other way would be to manually count all the all the elements:
$keys = array_keys($_POST);
$counted = count(preg_grep('/^Field_Amount_\d+$/', $keys));
If you also need to make sure you only track fields that are not empty then you could do supply an empty string as the second param to array_keys:
$keys = array_keys($_POST, '');
$counted = count(preg_grep('/^Field_Amount_\d+$/', $keys));
If you need to do more validation than that then you will need to manually loop.
if($_POST['Submit']) {
$count=0;
foreach( $_POST as $post ) {
if( strstr($post, "field_amount_")) {
$count++;
}
}
echo $count;
}

Categories