PHP $_POST Loop Multiple fields - php

I am trying to prepare a loop that will store the data from form fields below as a variable, that I can then use to create a new dynamic form based on this data.
FLOW EXAMPLE:
1. jquery submits hidden form in popup iframe(done)
2. PHP loops through POST from hidden form in iframe and outputs as new form in current popup iframe.
3. user selects the fields they wish to submit to database. Submits form.
4. database entry is added
5. selected fields are removed from current iframe. None selected are left.
I am stuck on the loop part of the code, I need an efficient solution that allows me to loop through POST and output a new form that the user can submit.
I know its alot to ask, but any help would be great, been banging my head against the wall trying to figure out how to do this. :(
Thanks,
Steve
PS. Sometimes there will be 10 fields, sometimes 2....it all depends on what is on the page when the iframe is created. But there will always be the same number of each field. Like in my field example below.
EXAMPLE OF FIELDS (all hidden)
<input type="hidden" id="data[]" name="data[]" value="SOMETHING HERE">
<input type="hidden" id="data[]" name="data[]" value="SOMETHING BLAH BLAH">
<input type="hidden" id="data[]" name="data[]" value="BLAH BLAH SOMETHING">
<input type="hidden" id="info[]" name="info[]" value="MY INFO HERE">
<input type="hidden" id="info[]" name="info[]" value="RANDOM INFO HERE">
<input type="hidden" id="info[]" name="info[]" value="MORE INFO">
<input type="hidden" id="img[]" name="img[]" value="http://example.com/img2.gif">
<input type="hidden" id="img[]" name="img[]" value="http://example.com/someimage.jpg">
<input type="hidden" id="img[]" name="img[]" value="http://example.com/myimage.png">
<input type="hidden" id="title[]" name="title[]" value="Item title goes here">
<input type="hidden" id="title[]" name="title[]" value="Item title goes here ">
<input type="hidden" id="title[]" name="title[]" value="Item title goes here">
MY PHP loop I tried:
foreach ($_POST['data'] as $data=>$val){
echo "$data: $val <br />";
}
foreach ($_POST['info'] as $info=>$val){
echo "$info: $val <br />";
}
foreach ($_POST['img'] as $img=>$val){
echo "$img: $val <br />";
}
foreach ($_POST['title'] as $title=>$val){
echo "$title: $val <br />";
}
EXAMPLE PHP Output
0: €29.16
1: €34.46
2: €34.46
3: €63.62
4: €53.02
5: €10.60
6: €42.42
0: ../img1.gif
1: ../img2.jpg
2: ../img3.jpg
3: ../img4.png
4: ../img5.gif
5: ../img6.jpg
6: ../img7.jpg
etc...
Example of how the output needs to be structured in the new form:
Item 1 Item 2 item 3 item 4
Title0 title1 title2 title3
info0 info1 info2 info3
img0 img1 img2 img3
data0 data1 data2 data3
checkbox checkbox checkbox checkbox
SUBMIT BTN

Use this code:
$items = array();
foreach($_POST['data'] as $key => $val)
{
$items[] = array(
'data' =>$_POST['data'] [$key],
'info' =>$_POST['info'] [$key],
'img' =>$_POST['img'] [$key],
'title' =>$_POST['title'] [$key] );
}

Name your input fields like this
<input type="hidden" id="data[]" name="data1" value="SOMETHING HERE">
<input type="hidden" id="data[]" name="data2" value="SOMETHING BLAH BLAH">
<input type="hidden" id="data[]" name="data2" value="BLAH BLAH SOMETHING">
Go through them like this:
<?php
$num = 1;
$data = array();
while (true) {
if (array_key_exists('data'.$num,$_POST)) {
$data[] = $_POST['data'.$num];
}
else {
break;
}
}
print_r($data); //outputs all data values
I hope I got your question correctly ;)

You should first do some business logic to get the data layout you need, and then use your newly formatted data to do what it is you are doing, i.e.
$items = array();
foreach ($_POST['data'] as $data=>$val){
$items[$data]['data'] = $val;
}
foreach ($_POST['info'] as $info=>$val){
$items[$info]['info'] = $val;
}
foreach ($_POST['img'] as $img=>$val){
$items[$img]['img'] = $val;
}
foreach ($_POST['title'] as $title=>$val){
$items[$title]['title'] = $val;
}
var_export($items);
and as long as you are only posting these particular values, you can actually condence this down to:
$items = array();
foreach($_POST as $part => $ar) {
if(is_array($ar) {
foreach($ar as $idx => $val) {
$items[$idx][$part] = $val;
}
}
}
var_export($items);

Related

Updating a specific key within a multidimensional array (PHP)

I'm having some difficulty updating a quantity value in a multi-dimensional array I've created and really hoping you can help me correct where I've gone wrong;
.
The background
I've got two "items" which both have a simple form tag followed by a hidden input field with a unique value (1 for the first item, 2 for the second).
The button will just point back to this same page using the POST method.
The div on the right of the page will then load a "basket" which will use these post values and add them to an array.
When the "add" button is used again the value should update to +1 rather than create another sub_array.
.
What is currently happening
Currently when I click "add" the first time it adds the array as expected;
However when clicking "add" for the second time it adds a second array rather than +1'in the quantity.
On the third time clicking "add" it does actually now find the original value and update it as I expected, if I click again and again it will continue to update the quantity
It just seems to be that second time I click "add".
.
The Script
<?php session_start();
function in_array_r($needle, $haystack, $strict = false) {
foreach ($haystack as $item) {
if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
return true;
}
}
return false;
}
if (ISSET($_POST["prod"]))
{
if(in_array($_POST["prod"],$_SESSION["cart"])==TRUE)
{
$_SESSION["cart"][0] =
array($_POST["prod"],$_POST["name"],$_SESSION["cart"][0][2]+1);
}
else{
echo 'running else';
$_SESSION["cart"]=array($_POST["prod"],$_POST["name"],1);}}
if ($_POST['e']=='1')
{
$_SESSION['cart'] = '';
}
echo '<br /><br />';
print_r($_SESSION["cart"]);
}
Sample form
<form action="test.php" method="post" enctype="application/x-www-form-urlencoded">
MAST-O-MIR<br/>
img<br/>
£2.00<br/>
<input type="hidden" value="1" name="prod" />
<input type="hidden" value="MAST-O-MIR" name="name" />
<button class="plus-btn" type="Submit">Add</button>
</form>
Also, what you might well notice from my script is that when you "add" the second item it will actually overwrite the first one by creating the array from scratch so if you can help me with either or both of these I really would appreciate the expertise!
Many thanks to all in advance!
I tried to debug your code and a possible solution could be the following:
<?php
session_start();
if(!isset($_SESSION["cart"]))
{
$_SESSION["cart"]=[];
}
if (isset($_POST["prod"]))
{
$prod_id=$_POST["prod"];
//let suppose $_POST['prod'] is your item id
$found=false;
for($i=0;$i<count($_SESSION['cart']);$i++)
{
if(isset($_SESSION['cart'][$prod_id]))
{
echo "found! so add +1";
$_SESSION['cart'][$prod_id][2]+=1;
$found=true;
break;
}
}
if($found==false)
{
echo 'not found! so create a new item';
$_SESSION["cart"][$prod_id]=array($_POST["prod"],$_POST["name"],1);
}
}
if (isset($_POST['e']) && $_POST['e']=='1')
{
$_SESSION['cart'] = '';
}
echo '<br /><br />';
print_r($_SESSION["cart"]);
?>
<form action="cart.php" method="post" enctype="application/x-www-form-urlencoded">
MAST-O-MIR<br/>
img<br/>
£2.00<br/>
<input type="hidden" value="1" name="prod" />
<input type="hidden" value="MAST-O-MIR" name="name" />
<button class="plus-btn" type="Submit">Add</button>
</form>
<form action="cart.php" method="post" enctype="application/x-www-form-urlencoded">
MAST-O-MIR<br/>
img<br/>
£2.00<br/>
<input type="hidden" value="2" name="prod" />
<input type="hidden" value="MAST-O-MIR" name="name" />
<button class="plus-btn" type="Submit">Add</button>
</form>
Another way to do it is using associative arrays.
The following code creates a cart array in $_SESSION using the item name as key(so you don't need to loop over the cart array to find the item) and
an array with properties as name=>value for each item.
session_start();
if(!isset($_SESSION["cart"]))
{
$_SESSION["cart"]=[];
}
//let's suppose you have unique names for items
if (isset($_POST["prod"]))
{
$name=$_POST["name"];
if(isset($_SESSION['cart'][$name]))
{
echo "found! so add +1";
$_SESSION['cart'][$name]['quantity']+=1;
}
else
{
echo 'not found! so create a new item';
$_SESSION["cart"][$name]=array("id"=>$_POST["prod"],"name"=>$_POST["name"],"quantity"=>1);
}
}
if (isset($_POST['e']) && $_POST['e']=='1')
{
$_SESSION['cart'] =[];
}
echo '<br /><br />';
print_r($_SESSION["cart"]);
?>
<form action="cart2.php" method="post" enctype="application/x-www-form-urlencoded">
MAST-O-MIR<br/>
img<br/>
£2.00<br/>
<input type="hidden" value="1" name="prod" />
<input type="hidden" value="MAST-O-MIR" name="name" />
<button class="plus-btn" type="Submit">Add</button>
</form>
<form action="cart2.php" method="post" enctype="application/x-www-form-urlencoded">
MAST-O-MIR<br/>
img<br/>
£2.00<br/>
<input type="hidden" value="2" name="prod" />
<input type="hidden" value="MAST-OMIR" name="name" />
<button class="plus-btn" type="Submit">Add</button>
</form>
It's hard to test your code without a sample form but I guess both of your problems may be solved by replacing:
$_SESSION["cart"][0] = array($_POST["prod"], $_POST["name"], $_SESSION["cart"][0][2]+1);
For:
$_SESSION["cart"][0][2]+= 1;
By the way, try to properly indent your code when you are going to post it. It is hard to read.

PHP parse array post

A page is posting an array to me like this:
<input type="text" name="fields[email_address][value]" value="1" />
<input type="text" name="fields[first_name][value]" value="jim" />
<input type="text" name="fields[zip_code][value]" value="45254" />...
An array.
I can loop through it like this easy enough
foreach ( $_POST['fields'] as $key => $field ) {
echo $key." ".$field['value'] ;
}
Result of above:
first_name jim
email_address 1
address_postal_code 45254
But what I really need to do is reference just the zip (45254) out of the array, maybe like:
echo $_POST['fields']['zip_code']; //or
echo $_POST['fields']['zip_code']['value'];
result: 45254
Is this possible?
Update
<input type="text" name="fields[zip_code][value]" value="45254" />
to be
<input type="text" name="fields[zip_code]" value="45254" />
Edit: I wasn't aware you can't modify the html, that wasn't specified in the original question.
The only thing you can really do is do:
$_POST['fields']['zip_code'] = $_POST['fields']['zip_code']['value'];
However at that point, you might as well just assign $_POST['fields']['zip_code']['value'] to a variable and use that.
If you can't update the html of the form, all you can do is manipulate the data after it's been assigned to the $_POST superglobal like it's any other array
Edit 2: Adding a complete snippet to try:
If you do, what do you get?:
<?php
foreach ( $_POST['fields'] as $key => $field ) {
echo $key." ".$field['value'] ."<br />";
}
echo $_POST['fields']['zip_code']['value'] . "<br />";
$_POST['fields']['zip_code'] = $_POST['fields']['zip_code']['value'];
echo $_POST['fields']['zip_code'];
?>
I just tried that with a simple form of:
<form method="post" action="test.php">
<input type="text" name="fields[email_address][value]" value="1" />
<input type="text" name="fields[first_name][value]" value="jim" />
<input type="text" name="fields[zip_code][value]" value="45254" />
<input type="submit" />
</form>
And it works as expected.
This seems sloppy but it worked:
foreach ( $_POST['fields'] as $key => $field ) {
$$key = $field['value'] ;
}
echo $address_postal_code;
45254
echo $_POST['fields']['zip_code']['value']
returns nothing

PHP: Process multiple textboxes with numbers at each end

I know how to process something like:
<input type="text" name="Textbox_T[]" id="txBox1" />
but I have an unknown number of boxes (they are generated via javascript and are only known to me after they are submitted) that are named like this:
<input type="text" name="Textbox_T1" id="txBox1" />
Textbox_T1
Textbox_T2
Textbox_T3
Textbox_T4
etc
since I cannot do:
$_GET['Textbox_T'.$i]
how do I do it?
You could set the textbox name to an array:
<input type="text" name="textboxes[]" />
<input type="text" name="textboxes[]" />
<input type="text" name="textboxes[]" />
<input type="text" name="textboxes[]" />
and then in the code
if (is_array($_GET["textboxes"])){
foreach ($_GET["textboxes"] AS $value){
echo $value." entered in a textbox.<br />";
}
}
edit: If you can not change the name, you could iterate over ALL
GEt-values:
foreach ($_GET AS $key=>$value){
if (strpos($key, "Textbox") === 0){
echo $value." has been entered in textbox ".$key."<br />";
}
}
Ideally you'd have the javascript add the textareas to submit as an array:
<textarea name="Textbox_T[]" ></textarea>
(I'm assuming you're talking about textareas) because then you just need to loop through that item in PHP once it's been submitted:
foreach($_GET['Textbox_T'] as $text){
//... do something
}
However, if you're stuck with it, you can just loop through your submitted _GET array and attempt to match based on a substring:
$prefix = "Textbox_T";
foreach($_GET as $key=>$value){
if (substr($key,0,strlen($prefix))==$prefix){
//this is one of them! do something
}
}

Get each chekbox group values into separate variables upon form submission

I have multiple checkbox groups, and once the form is submitted, I want each group of checkboxes that were selected to be added to their own variable.
This is the form:
<form action="" method="get">
<p>apple <input type="checkbox" value="apple" name="fruits[]" /></p>
<p>orange <input type="checkbox" value="orange" name="fruits[]" /></p>
<p>peach <input type="checkbox" value="peach" name="fruits[]" /></p>
<br>
<p>red <input type="checkbox" value="red" name="colors[]" /></p>
<p>green <input type="checkbox" value="green" name="colors[]" /></p>
<p>blue <input type="checkbox" value="blue" name="colors[]" /></p>
<br>
<p>chicken <input type="checkbox" value="chicken" name="meats[]" /></p>
<p>pork <input type="checkbox" value="pork" name="meats[]" /></p>
<p>lamb <input type="checkbox" value="lamb" name="meats[]" /></p>
<button>submit</button>
</form>
And this is my code:
$string = 'fruits,colors,meats';
$str_array = explode(',', $string);
foreach ($str_array as $value) {
if (isset($_GET[$value])) {
$group_name = $_GET[$value];
foreach ($group_name as $group_item) {
$group_string .= ' ' . $group_item;
}
}
}
echo $group_string;
With that code, if I choose for example the first checkbox in each group and hit submit, I will get the following value of $group_string = apple red chicken in one string.
What I get does make sense to me as per the code I wrote, but what I want is for each option group to have its own variable to which its values are asigned, so what I want is to get is the following (assuming I again chose the first option from each group):
$fruits = 'apple';
$colors = 'red';
$meats = 'chicken';
But I don't know how to rewrite it so I get that. Also, the number of options groups is not known upfront, it has to happen dynamically.
Ok, I took the liberty of rewriting part of your php for my convenience but here it is
your new and improved php file
<?php
// assume we know beforehand what we are looking for
$groups = explode(',','fruits,colors,meats');
foreach ($groups as $group) {
if (isset($_GET[$group])) {
$vv = array();
foreach ($_GET[$group] as $item) $vv[] = $item;
$$group = implode(' ',$vv);
}
}
var_dump($fruits,$colors,$meats);
?>
I used a construct in PHP called variable variables. This is actually an almost identical answer as the one #Lohardt gave. I hope this can help you out. If it doesn't then post me a comment
You could do something like:
<input type="checkbox" value="apple" name="groups[fruits][]" />
<input type="checkbox" value="apple" name="groups[colors][]" />
<input type="checkbox" value="apple" name="groups[meats][]" />
Your $_POST will look like this:
Array
(
[groups] => Array
(
[fruits] => Array
(
[0] => apple
)
[colors] => Array
(
[0] => red
)
)
)
And it should be simple to use a foreach loop to get the keys and values.
Edit: then you can assign the value to variables like this:
${$key} = $value;
and use it you would do any variable:
echo $color;

PHP implode function not working right

So I am trying to email the results of a form using PHP. inside my form I have a bunch of checkboxes. The script below works when at least 1 checkbox in a group is checked. If none of the checkboxes are checked I receive the following error:
Warning: Implode() [function.implode]: Invalid augments passed in {name of php doc} on line {xxx} Array
Here is a sample of the code I'm using:
<?php
$data = array();
foreach ($_POST as $key => $value) {
$data[] = $value;
}
if(!$data[14]) //$data[14] is an array of checkbox values
{echo 'No User Selection';}
else
{echo implode(" | ", $data[14]);} //This is where the error occurs
?>
HTML code
<label for="b0" class="left">Item 1</label>
<input type="checkbox" name="b[0]" id="b0" value="Item 1"/>
<label for="b1" class="left">Item 2</label>
<input type="checkbox" name="b[1]" id="b1" value="Item 2"/>
<label for="b2" class="left">Item 3</label>
<input type="checkbox" name="b[2]" id="b2" value="Item 3"/>
ect....
Does anyone have an idea why I'm receiving this error?
Make sure the variable a) is set and b) is an array.
$data = array();
foreach ($_POST as $key => $value) {
$data[] = $value;
}
if ( !isset($data[14]) || !is_array($data[14]) ) {
echo 'No User Selection';
} else {
echo implode(" | ", $data[14]);
}
Always properly check variables using isset(), unless of course you like giant error logs! I also suggest using the $_POST keys as the keys for $data, thus making life even easier when you want to look up a specific $_POST item.
If the checkbox is not checked, it is not sent to the server.
I suggest you to do something like this:
<label for="b0" class="left">Item 1</label>
<input type="hidden" name="b[0]" value=""/>
<input type="checkbox" name="b[0]" id="b0" value="Item 1"/>
<label for="b1" class="left">Item 2</label>
<input type="hidden" name="b[1]" value=""/>
<input type="checkbox" name="b[1]" id="b1" value="Item 2"/>
<label for="b2" class="left">Item 3</label>
<input type="hidden" name="b[2]" value=""/>
<input type="checkbox" name="b[2]" id="b2" value="Item 3"/>
This way, you are sure that b[0], b[1], etc. are always sent
You are causing the problem yourself by making the data array. Just go straight to the POST array. Everything else is overcomplicating the problem.
<?php
if(!isset ($_POST['b']) || !is_array($_POST['b'])) {
echo 'No User Selection';
} else {
echo implode(" | ", $_POST['b']);
}
?>
In addition, if the content of your form changes slightly, or you want to reorder the fields then your magic number 14 will no longer work.
Your code will be unbelievably fragile unless you change it.

Categories