parsing dynamic POST variable - php

I have a form that may submit 1 line item or 200 to quote. using FPDF to create results and everything is working perfectly, but I was looking for a way to automate picking up post values. So far I have been doing them manually, which is very difficult to make code changes:
//conditional statement to verify values exist, otherwise we write a blank line
$item=$_POST['item3'];
$uprice=$_POST['uprice3'];
$udprice=$_POST['udprice3'];
$quan=$_POST['quan3'];
//add values to report
//repeat for next result
$item=$_POST['item4'];
$uprice=$_POST['uprice4'];
$udprice=$_POST['udprice4'];
$quan=$_POST['quan4'];
I was wondering if there is a way to add a variable inside the post value, like $_POST[$nextitem]?

You can loop until the next number is not available anymore:
<?php
$i = 1;
while (isset($_POST['item' . $i])) {
$item = $_POST['item' . $i];
$uprice = $_POST['uprice' . $i];
$udprice = $_POST['udprice' . $i];
$quan = $_POST['quan' . $i];
// do your stuff
$i++;
}
concatenating a string 'var' with int 1 will result in a string 'var1' in PHP.

I would just grab the entire array with $array = $_POST and then use foreach() loops to manipulate it later.
Alternatively, it sounds like you have an arbitrary number of things on your form. Do it like this:
<input type="text" name="item[]" />
<input type="text" name="quan[]" />
<input type="text" name="udprice[]" />
<input type="text" name="item[]" />
<input type="text" name="quan[]" />
<input type="text" name="udprice[]" />
<input type="text" name="item[]" />
<input type="text" name="quan[]" />
<input type="text" name="udprice[]" />
<input type="text" name="item[]" />
<input type="text" name="quan[]" />
<input type="text" name="udprice[]" />
You can see more about this in this very helpful answer: HERE
When you submit this arbitrary number of fields, you will end up with a nice multi-dimensional array. Iterate over it like this:
$i = count($_POST['item']);
$payload = array();
while ($i <= count($_POST['item']) {
$payload[] = array(
'item' => $_POST['item'][$i],
'udprice' => $_POST['item'][$i],
'quan' => $_POST['quan'][$i]
);
$i++;
}
Now $payload is a fancy array that can be inserted into databases and such.

Related

How to POST an associative array in PHP

I have the following form:
<form action="options.php" method="post">
<input type="text" name="deptid" id="deptid" />
<input type="text" name="deptname" id="deptname" />
<input type="submit" name="submit" id="submit" value="save" />
</form>
EDIT
Is it possible to pass the two values into one associative array BEFORE submission ?
I would like to pass it in this form:
array('deptid'=>'deptname')
I need this because I avoid to modify the script of the destination php file(options.php)
Thanks.
Here is a method using pure HTML that get's you nearly exactly where you want to be, and only uses HTML:
<form action="options.php" method="post">
<input type="text" name="options[deptid]" id="deptid" />
<input type="text" name="options[deptname]" id="deptname" />
<input type="submit" name="submit" id="submit" value="save" />
</form>
Which would give you in PHP:
$post_options = array(
'options' => array(
'deptid '=> '[that input element value]',
'deptname' => '[that input element value]'
)
);
Which you can then (including sanitizing) access such as this:
$post_options = array('options');
if (is_numeric($post_options['deptid'] && $post_options['deptid'] > 0) {
// Do whatever
}
if (is_string($post_options['deptname'] && strlen($post_options['deptname'] > 2)) {
// Do whatever
}
EDIT
Or... You want to reference the deptid in the input name attribute and use it to modify the row for a department name? Which seems to indicate something like this:
<?php
$deptid = 1;
$deptname = 'Department of Silly Walks';
?><input type="hidden" name="options[<?=$deptid?>]" value="<?=$deptname?>">
Which outputs:
<input type="hidden" name="options[1]" value="Department of Silly Walks">
http://codepad.org/DtgoZGe7
The problem with this is that the $deptid value becomes a value that's not actually directly named or referenced. I think this is potentially problematic to implement due to this abstraction of the value from the server to the client and back, so I would recommend what I have at the top instead. It's not much of a difference in practice, but it's more or less self-documenting.
Note, if you wanted to serialize a list of departments, it's a little trickier. You might, for instance, try this:
<input type="text" name="options[][deptid]" id="deptid" />
<input type="text" name="options[][deptname]" id="deptname" />
Which would add an indexed value for every input. However... They were would not be directly associated. So you would get, instead, two zero-indexed arrays for each key.
What I would suggest in this case is to use Javascript to add each new department's input elements, so you can give each a number like:
<input type="text" name="options[0][deptid]" id="deptid" />
<input type="text" name="options[0][deptname]" id="deptname" />
<br/>
<input type="text" name="options[1][deptid]" id="deptid" />
<input type="text" name="options[1][deptname]" id="deptname" />
<br/>
<input type="text" name="options[2][deptid]" id="deptid" />
<input type="text" name="options[2][deptname]" id="deptname" />
<br/>
<input type="text" name="options[3][deptid]" id="deptid" />
<input type="text" name="options[3][deptname]" id="deptname" />
Or do the old-school POSTBACK method and use PHP to count $POST['options'] and "manually" add a new "row" of inputs with the same index. It's a common trap, so you just have to think about it if this is what you're after at some point.
$_POST is already an associative array and I recommend you not to complicate things beyond that because $_POST already holds the data came from your form.
$myassoc = $_POST;
print_r($myassoc);
and the associative array that you will receive is organized and named same in the name attribute of the input elements in your form (including textarea)
Other Insights
As I see your code you want to put the deptname data to deptid as it reaches the PHP server-side code. well the thing you can do with is is just assign it to the key deptid
$_POST['deptid'] = $_POST['deptname'];
$myassoc = $_POST;
print_r($myassoc);
<form method="post">
<input type="text" name="formdata['deptid']" />
<input type="text" name="formdata['deptname']" />
<input type="submit" />
</form>
<?php
if(isset($_POST['formdata']))
{
$deptid = $_POST['formdata']['deptid'];
$deptname = $_POST['formdata']['deptname'];
}
?>
Build a JS object with the appropriate structure, convert it to JSON with JSON.stringify(), POST it, and then do json_decode($_POST['data'],true).
You'll have an exact copy from JS object, to PHP associate array. Drop the second parameter of true to get a PHP object.
$_POST is already an associative array.
You can rebuild an array of the form you need from this by just assigning $_POST to a variable
$myarray = $_POST;
Now $myarray is what you require. Do var_dump($myvar);.
Why would you want to do that?
But, you CAN send "arrays" through forms like this:
<form method="post">
<input type="text" name="textboxes[]" />
<input type="text" name="textboxes[]" />
<input type="submit" />
</form>
<?php
if(isset($_POST['textboxes']))
var_dump($_POST['textboxes']);
?>
$deptid = $_POST['deptid'];
$array = array($$deptid => $_POST['deptname']);
print_r($array);

Passing arrays from HTML form to PHP

This is the HTML:
<input type="text" name="shortcut[]" value="a"/> do <input type="text" name="ses[]" value="1" disabled/><br>
<input type="text" name="shortcut[]" value="b"/> do <input type="text" name="ses[]" value="2" disabled/><br>
<input type="text" name="shortcut[]" value="c"/> do <input type="text" name="ses[]" value="3" disabled/><br>
How do I pass the values to PHP but connect the indexes of both arrays?
i.e. put in database value 1 where something = a,
put in database value 2 where something = b
and so on ...
The indexes are connected automatically, since they're numeric arrays.
$nvals = count($_REQUEST['shortcut']);
for ($i = 0; $i < $nvals; $i++) {
// do something with $_REQUEST['shortcut'][$i] and $_REQUEST['ses'][$i]
}
Combined array: array_map(null,$_POST['shortcut'],$_POST['ses']);
But you could of course could foreach over one of the 2, and fetch the other by key.
Note that if you have elements which may or may not be sent (checkboxes for instance), the only way to keep groups together is to assign them a number beforehand (name=sess[1], name=sess[2], etc.)
You can specify shortcut value as the key and the ses value as the value attribute:
<input type="text" name="input[a]" value="1" />
<input type="text" name="input[b]" value="2" />
<input type="text" name="input[c]" value="3" />
On the server-side you could use a foreach loop to iterate over the array:
foreach ($_POST['input'] as $shortcut => $ses) {
// process $shortcut and $ses
}

PHP How to GET the Form variables on multiple items?

I need to collect the form elements of a cart. The items are in multiples. I wish to collect them as a session or easy to use Array - I think the Array would be best?
How can I collect this information in process.php?
I hope I have made it clear.
The code is like this for each item:
<div class="product" id="pId_'.$id.'">
<input type="hidden" name="productID" value="'.$id.'" />
<input type="hidden" name="productURL" value="'.$url.'" />
<input type="hidden" name="productQty" value="'.$qty.'" />
<input type="hidden" name="productPrice" value="'.$price.'" />
</div>
So the use cart could have :
<div class="product" id="pId_2">
<input type="hidden" name="productID" value="2" />
<input type="hidden" name="productURL" value="site.com" />
<input type="hidden" name="productQty" value="1" />
<input type="hidden" name="productPrice" value="750" />
</div>
<div class="product" id="pId_45">
<input type="hidden" name="productID" value="45" />
<input type="hidden" name="productURL" value="example.co.uk" />
<input type="hidden" name="productQty" value="2" />
<input type="hidden" name="productPrice" value="100" />
</div>
These details are submitted to the form.. but how can I collect when productID is called twice or more?
If you just need to collect the items for processing later, another way of doing it is to loop through all the POST variables. PHP will collect all information submitted into a reserved variable, $_POST.
From there you could use a foreach to loop through the information collected as follows;
foreach ($_POST as $key => $value)
{
echo "$key = $value";
}
Where $key would be your someitem_ and $value would contain the actual value submitted.
This would work easier provided you did not have any other inputs in your form other then those of the shopping cart items, if not you'll have to do some logic to determine which were the records that were associated with your cart items.
On a side note, if it is possible to combine the 3 related input values into just 1, with the values separated by a character you defined (maybe something like <item>|<name>|<url>), it might make your life easier when trying to get all the 3 values that are associated with the id.
In that case your code would just get the string value for the specific id and do a split() on the '|' to break it up back into its 3 values.
If you add square-brackets to your input names
<input type="hidden" name="productID[]" value="' . $id . '" />
<input type="hidden" name="productURL[]" value="' . $url . '" />
<input type="hidden" name="productQty[]" value="' . $qty . '" />
<input type="hidden" name="productPrice[]" value="' . $price . '" />
you can then collect and use all form data by adding the following PHP code to your process.php file
foreach ($_POST['productID'] as $key => $getid) {
$getqty = $_POST['productQty'][$key];
$getprice = $_POST['productPrice'][$key];
$geturl = $_POST['productURL'][$key];
// Example MySQL Query
mysql_query("INSERT INTO orders (id, url, quantity, price) VALUES ('" . $getid . "', '" . $geturl . "', '" . $getqty . "', '" . $getprice . "')");
}
What this does is that it automatically creates arrays for the form data so that you can, using the PHP code above, collect the correct data from each row by using the index number via the $key variable.
I believe in your process.php form you could just store them in an array when you pull in the post data. You will need to pass the largest value of $id as a value as well so you can loop through the appropriate amount of items.
The top of your process.php might look like
<?php
$processArray = array();
$id = $_POST["id"];
$i = 0;
while ($i <= $id) {
$processArray = ('item' => $_POST["someitem"_.$i], 'name' => $_POST["somename"_.$i], 'url' => $_POST["someurl"_.$i]):
//Now you can do what you want with each value. Display it somewhere, store it somewhere, etc.
$i++;
}
I did this off the top of my head but that's what comes to mind when I look at your issues.
I'm not entirely sure of what you're asking. But you can retrieve arrays from $_POST if the field names are appended with [].
<input name="myArray[1]" value="foo" />
<input name="myArray[37]" value="bar" />
Would give you
array(
1 => 'foo',
37 => 'bar'
)
<form action="process.php" method="post">
These elements are looped pending on cart items
<input type="hidden" name="someitem['.$id.']" value="1" size="1" maxlength="1" />
<input type="hidden" name="somename['.$id.']" value="1" size="1" maxlength="1" />
<input type="hidden" name="someurl['.$id.']" value="1" size="1" maxlength="1" />
</form>
Use:
<input type="hidden" name="someitem[]" value="1" size="1" maxlength="1" />
And then in PHP $_GET["someitem"] will be an array
EDIT: Use $_POST["someitem"]. I had assumed you needed GET, because of the title of the question.

Combining form textfield values using php implode

I have 3 text fields and I want to pass the values after combining them using a hyphen.
<input type="text" name="val[]" />
<input type="text" name="val[]" />
<input type="text" name="val[]" />
Preferably help me with php implode option.
How do i retrieve it after submit ?
Thanks.
After sending the form, your values will be in $_POST['val'] or $_GET['val'] as an array, depending on the method of your form.
You can combine them simply by:
$hyphenated = implode("-", $_POST['val']); // or $_GET['val']
thanks. how do i change focus to next field once a field has max values:
See if this works:
<input type="text" name="val[]" onkeyup='checkVals("field1", "field2");' id='field1'>
<input type="text" name="val[]" onkeyup='checkVals("field2", "field3");' id='field2'>
<input type="text" name="val[]" id='field3'>
<script>
function checkVals(this_field, next_field){
var fieldval = document.getElementById(this_field).value;
var fieldlen = fieldval.length;
if(fieldlen > 10){ // you can change 10 to something else
document.getElementById(next_field).focus();
document.getElementById(next_field).select();
}
}
</script>

Accessing multiple cloned fields from PHP

I have a form which has the ability to copy a row of several fields using jquery - my question is how do I access these form values in the target php page?
Any code, by chance? Anyway, you can make it add a name to the new field with square braces, so ti will be accessed as an array, like it happens with multiselect checkboxes
es: new field 1 <input type="text" name="added[]" value="">
new field 2 <input type="text" name="added[]" value="">
and so on...
Then you have everythin in the $_POST['added'] array
If they have the same 'name' attribute value, change that value to 'name[]' so that they look like
<input type="text" name="name[]" />
<input type="text" name="name[]" />
<input type="text" name="name[]" />
<input type="text" name="name[]" />
//etc...
and you should be able to access them by using:
$value = $_POST['name'][0];
where 0 is the index of the field, IE, the first field is 0, second is 1...
It is easier to access these using a for loop
for($i = 0; $i < count($_POST['name']; $i++)
// actions with $_POST['name'][$i]
or a foreach loop.
foreach($_POST['name'] as $value)
// actions with $value
Depends on how jquery is adding them. Do the following on the called page and see how they're being passed through.
var_dump( $_POST ); // Or maybe $_GET

Categories