Using a Form With Variables as Part of a Function - php

Could the form below be part of a function? I am wondering if it might not be able to be part of a function since it has variables.
Thanks in advance,
John
echo '<form action="http://www...com/sandbox/comments/comments2.php" method="post">
<input type="hidden" value="'.$_SESSION['loginid'].'" name="uid">
<input type="hidden" value="'.$submissionid.'" name="submissionid">
<input type="hidden" value="'.$submission.'" name="submission">
<input type="hidden" value="'.$url.'" name="url">
<input type="hidden" value="'.$submittor.'" name="submittor">
<input type="hidden" value="'.$submissiondate.'" name="submissiondate">
<input type="hidden" value="'.$countcomments.'" name="countcomments">
<input type="hidden" value="'.$dispurl.'" name="dispurl">
<label class="addacomment" for="title">Add a comment:</label>
<textarea class="commentsubfield" name="comment" type="comment" id="comment" maxlength="1000"></textarea>
<div class="commentsubbutton"><input name="submit" type="submit" value="Submit"></div>
</form>
';

You can use that code in a function provided that:
You pass those parameters ($submissionid, $submission etc) to the function
or
You make them global (you shouldn't do this without strong reason)

There's three basic choices for passing form arguments into a function:
massive argument list
stuff the values into an array and passing that in
global variables
Generally only #2 will keep your hair from getting yanked out (by yourself or other people). The basic setup would go something like:
function show_form($args) {
echo <<<EOL
<form action="yada yada">
<input type="..." name="field1" values="{$args['field1']}" />
<input type="..." name="field2" values="{$args['field2']}" />
etc...
</form>
EOL;
}
$form_args = array(
'field1' => $field1,
'field2' => $field2,
etc...
)
show_form($form_args);
Note that I'm using a HEREDOC to generate the form text. It's far easier to deal with than building a string with concatenation. It saves you from having to worry about escaping quotes.
If this form deals with potentially hostile users, you'll want to pass all the values through htmlspecialchars() beforehand, to prevent some HTML injection attacks. You can do that within the form building function, or while you're building the argument array.
comment followup:
In this example, you're building array called "form_args" to store all the field data of your form. I'm just calling them "field1", "field2" etc... You pass those $form_args array as a parmeter to the show_form() function. Within the function, it accesses that data via its own private little "$args" copy of the array.
Within the form, the notation {$args['field1']} simply means "Look in the $args array for an entry whose key is 'field1', and insert its matching value into the HTML being generated here. The braces ({}) aren't strictly necessary in this case, but could be considered good practice to use anyways. There's more details in the PHP online manual's Arrays entry

Related

proper structure for array of form field names for both jquery validation and php processing

The simplified form in the html code below contains a number of repetitive form fields which must be both validated by means of some jquery validate code and processed by means of some php code...I have set up the form field below to facilitate the php processing, but then again get stuck with writing the proper jquery validate code as the 'name' tags are supposed to be unique. If I'd make the name tags unique I think the php coding becomes more complex.
Just wondering what a proper structure of repetitive form fields would be which facilitates both the jquery validation coding and php coding?
Any suggestions?
Thank you in advance.
html code:
<input type="checkbox" id="check0" name="productselection[]" value="productselected0">
<input id="nrofparts0" type="text" name="nrofparts[]">
<input type="checkbox" id="check1" name="productselection[]" value="productselected1">
<input id="nrofparts1" type="text" name="nrofparts[]">
<input type="checkbox" id="check2" name="productselection[]" value="productselected2">
<input id="nrofparts2" type="text" name="nrofparts[]">
heres one way you can do it:
HTML
<form id="theForm" method="post">
<input type="checkbox" name="checky[0]" />
<input type="checkbox" name="checky[1]" />
<input type="checkbox" name="checky[2]" />
<input type="submit" name="submit" value="submit"/>
</form>
I add a key to the array because it makes it easier to determine which checkboxes were clicked. you wont get anything for an unclicked one. that can make it confusing
jquery:
$('#theForm input[type="checkbox"]').each(function(){
// if($(this))... some validation
});
php:
if(isset($_POST['checky'])){
foreach($_POST['checky'] as $key => $val){
echo $key.' '.$val; // this will give you the key of the checkbox, and the value
}
}
you could also have a hidden input that counts the checkboxes. That way when you loop, you can use it to set the empty checkboxes in your php code.
hope this helps!

Dynamically add to array in PHP?

I am trying to take input from a form, add it to an array, and print_r that array to the screen.
My problem is that the input from the form only replaces the first (and only) element in the array.
<form action="" method="POST">
<input type="text" name="text" />
<input type="submit" name="sub"/>
</form>
<?php
$a = array();
if( isset($_REQUEST['text']) && !empty($_REQUEST['text'])){
array_push($a, $_REQUEST['text']);
print_r($a);
}
?>
One theory of mine is that $a keeps getting re-assigned on the first line of PHP code ($a = array();), but I'm not sure how to fix it. I have looked around, but can't find an answer.
You are correct. The array does get reinitialized each time the form is posted. What you'll want to do is have your array as a more persistent data source.
You might consider using a session and the $_SESSION variable.
session_start();
if (!is_array($_SESSION['a'])){
$_SESSION['a'] = array();
}
$_SESSION['a'][] = $_REQUEST['text'];
You might also consider writing this data to a small text file that you could then read at the start of the script.
Another option would be to write the data to a $_COOKIE.
You are mixing client and server execution...
If you want an array of text you should use something like this:
<form action="" method="POST">
<input type="text" name="text[]" />
<input type="text" name="text[]" />
<input type="text" name="text[]" />
<input type="submit" name="sub"/>
</form>
If you want more entry of text being added you should inject more input with javascript
You are not replacing anything, what you're doing is adding the value of $_REQUEST['text'] to the array, which was empty before.

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

Store values from dynamically created inputs to a PHP variable

I have a page that allows the user to add and remove text fields to a form using JavaScript.
Text fields are named field1, field2, field3, etc. and depends on how many fields the user has added
I'm trying to store all the values from my text fields into one Php variable;
I understand that i need to store them into an array first and then use implode(), but how can i specify how many inputs there are within my Php code?
Usually the best way to approach this is to use array-named input, as shown in the following example in the PHP docs:
<form action="" method="post">
Nombre: <input type="text" name="personal[nombre]" /><br />
Email: <input type="text" name="personal[email]" /><br />
Cerveza: <br />
<select multiple name="cerveza[]">
<option value="warthog">Warthog</option>
<option value="guinness">Guinness</option>
<option value="stuttgarter">Stuttgarter Schwabenbräu</option>
</select><br />
<input type="submit" value="submit me!" />
</form>
You could use the very same name for each of the user added fields, as in:
<input type="text" id="field1" name="fields[]" />
<input type="text" id="field2" name="fields[]" />
And then just use implode as required:
$imploded_fields = implode(', ', $_POST['fields']);
There are many options:
You can use cookies. Use PHP $_COOKIE to get it. For help.
You can use html hidden input fields - <input type="hidden" value=""> and can store actual number of fields in it.
But, Diego Agulló is better one
You can create a hidden field and initialize it with 1 if on option is already open(field1). And increase the the value of counter while increasing the value of fields and vise verse. On submit you will find the total fields added.
Thanks

reading two form elements with same name

<form action="test.php" method="post">
Name: <input type="text" name="fname" />
<input type="hidden" name="fname" value="test" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
How can I read the values of both the fields named fname?
On my action file(test.php) under $_POST, I am getting only hidden field value.
Is there any PHP setting through which I can read both values?
I believe you want to name the fields as:
Name: <input type="text" name="fname[]" />
<input type="hidden" name="fname[]" value="test" />
to make PHP understand them as an Array.
In case someone wants to do this and doesn't want to change the name of the form elements, or can't, there is still one way it can be done - you can parse the $_SERVER['QUERY_STRING'] or http_get_request_body() value directly.
It would be something like
$vals=explode('&',http_get_request_body());
$mypost=Array();
foreach ($vals as $val) {
list($key,$v)=explode('=',$val,2);
$v=urldecode($v);
$key=urldecode($key);
if ($mypost[$key]) $mypost[$key][]=$v;
else $mypost[$key]=Array($v);
}
This way $mypost ends up containing everything posted as an array of things that had that name (if there was just one thing with a given name, it will be an array with only one element, accessed with $mypost['element_name'][0]).
For doing the same with query strings, replace http_get_request_body() with $_SERVER['QUERY_STRING']
If you want to pass two form inputs with the same name, you need to make them an array. For example:
<input type="text" name="fname[]" />
<input type="hidden" name="fname[]" value="test" />
You can then access it using the following:
$_POST['fname'][0]
$_POST['fname'][1]
You might want to rethink whether you really need to use the same name though.
Solutions are
1) Try using different name for textbox and hidden value
2) Use an array as mentioned above for field name
3) Its not possible as the values will be overwritten if the names are same

Categories