How to handle $post_[] on all inputs - php

What's the ideal way to handle an input form with multiple values, without going through each $POST_['inputname'] individually?
For example, let's say I have an invite form like this:
<form id="input-form" action="" method="post" >
<input id="email_1" name="email_1" />
<input id="role_1" name="role_1" />
<input id="email_2" name="email_2" />
<input id="role_2" name="role_2" />
<input id="email_3" name="email_3" />
<input id="role_3" name="role_3" />
</form>
Ideally, I'd like to create two arrays with the data, one for the email addresses and another for the roles
The resulting arrays would look like this:
$emailArray = array(
'email1' => "emailOneData",
'email2' => "emaiTwoData",
'email3' => "emaiThreeData",
);
$RoleArray = array(
'role1' => "roleOneData",
'role2' => "roleTwoData",
'role3' => "roleThreeData",
);
Not sure what the best way of splitting the data is though. Also I don't really want to do something like this:
$_POST['email_1']
$_POST['email_2']
$_POST['email_3']
.....

Use instead an $_POST Array.
<form id="input-form" action="" method="post" >
<input id="email_1" name="email[]" />
<input id="role_1" name="role[]" />
<input id="email_2" name="email[]" />
<input id="role_2" name="role[]" />
<input id="email_3" name="email[]" />
<input id="role_3" name="role[]" />
</form>
After this you got an array like this:
echo'<pre>';
print_r($_POST['email']);
print_r($_POST['role']);
echo'</pre>';
Of course you still have to escape your input in dependency of your use.
After this you can use a normal foreach on the array.
$mails=array();
$count=count($_POST['role']);
for($i=0;$i<$count;$i++){
$mails["email_".$i]=$_POST['role'][$i];
}

Related

Is there any better way to change the style of an element with PHP?

Is there any better way to achieve the same result, by using PHP externally instead of inside the actual HTML tag? This method works fine, but it seems a little inconvenient to place PHP tags inside HTML tags like this. Especially when you have to adjust multiple attributes when submit is clicked. Or worse, multiple attributes of multiple elements in the same form!
As an absolute PHP beginner I have no clue...
<form method="post" action="">
<input type="text" name="input" value="
if (isset ($_POST['submit']) ) {
$input = $_POST['input'];
echo $input;
}
" />
<input type="submit" name="submit" />
</form>
Please note:
The script above may be faulty, because I wrote it directly into this forum post without testing it externally. I am merely trying to point out the idea of it: Adjusting the style, value or any other attribute using PHP only.
If you don't want to put your PHP logic in your HTML code, you could write the php logic above the HTML code and store the result in a variable which you can then put in the HTML code.
For example:
<?php
$input = '';
if (isset ($_POST['submit']) ) {
$input = $_POST['input'];
}
?>
<form method="post" action="">
<input type="text" name="input" value="<?php echo $input; ?>" />
<input type="submit" name="submit" />
</form>
If you need to make your code shorter you can use short tags
<form method="post" action="">
<input type="text" name="input" value="<?= isset ($_POST['submit']) ? $_POST['submit'] : '' ?>" />
<input type="submit" name="submit" />
</form>
You may provide all you need before rendering
<?php
$html = [
'forms' => [
'myForm' => [
'action' => '',
'method' => 'POST',
'myInput' => [
'value' => isset ($_POST['submit']) ? $_POST['submit'] : ''
],
],
],
];
?>
<form method="<? $html['forms']['myForm']['method'] =?>" action="<?= $html['forms']['myForm']['method'] ?>">
<input type="text" name="input" value="<?= $html['forms']['myForm']['myInput']['value'] ?>" />
<input type="submit" name="submit" />
</form>
Also there is some tools so you can use php within your html more readable.
Using PHP as a template engine

Foreach input php and mysql

I know there are similar topics out there but haven't been able to find what I'm looking for. So what I need to do is target a specific input name and foreach loop only that input instead of the whole form.
HTML look something like below.
<form action"<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data" name="table1" method="post">
<input name="something1" type="text" />
<input name="something2" type="text" />
<input name="something3" type="text" />
<input name="something4" type="text" />
<input name="something4" type="text" />
<input name="something4" type="text" />
<input name="button" type="submit" value="Add" />
</form>
So I wanna loop every "something4" and just ignore the rest. Is this possible?
Just to explain what I want to do with the value is for every "something4" I'm gonna add a field to my DB and the input the respective input value into that field.
something like below...
$i = 0;
foreach ($_POST as $something4 => $something4_value) {
$add = mysqli_query($connect, "ALTER TABLE 'table' ADD something4$i VARCHAR( 255 ) NOT NULL") or die (mysql_error());
$sql_update = mysqli_query($con, "UPDATE 'table' SET something4$i='$something_value' WHERE id='$id'") or die (mysql_error());
$i++;
}
I hope this make sense! Thank you! :)
Create each of the name="something4" into an array like this:
<input name="something4[]" type="text" />
Then you can do a
foreach($_POST['something4'] as $something4) {
}

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

alter $_POST data of radio select option

So I have a Radio button group, like so:
<div data-role="fieldcontain">
<fieldset data-role="controlgroup">
<legend>Choose a pet:</legend>
<input type="radio" name="radio-choice-1" id="radio-choice-1" value="choice-1" checked="checked" />
<label for="radio-choice-1">Cat</label>
<input type="radio" name="radio-choice-1" id="radio-choice-2" value="choice-2" />
<label for="radio-choice-2">Dog</label>
<input type="radio" name="radio-choice-1" id="radio-choice-3" value="choice-3" />
<label for="radio-choice-3">Hamster</label>
<input type="radio" name="radio-choice-1" id="radio-choice-4" value="choice-4" />
<label for="radio-choice-4">Lizard</label>
</fieldset>
</div>
Now if I just submit the for I get this $_POST (Note I have multiple Radio group questions)
Array
(
[radio-choice-1] => choice-1
[radio-choice-2] => choice-4
[radio-choice-3] => choice-2
[submit] => submit
[PHPSESSID] => 11111111111111111
)
How Can I restructure the HTML or $_POST data before submission to make it look like this:
Array
(
[type-1] => radio-choice-1
[answer-1] => choice-1
[type-2] => radio-choice-2
[answer-2] => choice-4
[type-3] => radio-choice-3
[answer-3] => choice-2
[submit] => submit
[PHPSESSID] => 11111111111111111
)
Maybe jQuery as an option?
You can do it post submission, the code below should work if you keep your original naming conventions.
$postValues = $_POST;
$altered = Array();
$unaltered = Array();
foreach ($postValues as $key => $val) {
if ( FALSE !== stripos($key, 'radio-choice-') ) {
$num = explode('-', $key);
$num = $num[2];
$altered['type-'.$num] = $key;
$altered['answer-'.$num] = $value;
} else {
$unAltered[$key] = $value;
}
}
$manipulatedPOSTData = array_merge($altered, $unAltered);
// Keep doing what you intended
I assume you are talking about a form that you are submitting?
If you want to add finer control over what gets posted, you can do one of two things:
1) add hidden variables
or
2) use jQuery .post() (http://api.jquery.com/jQuery.post/) instead of doing a normal form submission.
Personally, I think the first of the two is simplest:
<div data-role="fieldcontain">
<input type="hidden" name="type-1" value="radio-choice-1" />
<fieldset data-role="controlgroup">
<legend>Choose a pet:</legend>
<input type="radio" name="answer-1" id="radio-choice-1" value="choice-1" checked="checked" />
<label for="radio-choice-1">Cat</label>
<input type="radio" name="answer-1" id="radio-choice-2" value="choice-2" />
<label for="radio-choice-2">Dog</label>
<input type="radio" name="answer-1" id="radio-choice-3" value="choice-3" />
<label for="radio-choice-3">Hamster</label>
<input type="radio" name="answer-1" id="radio-choice-4" value="choice-4" />
<label for="radio-choice-4">Lizard</label>
</fieldset>
</div>
By changing the name of the radio ground to answer-1 and adding a hidden variable, that should meet your requirements (do the same for your other radio elements).
Avoid client side elaboration if you can.
Otherwise use .submit() and hand code what you need. but it's harder.

Is it possible to group $_POST variables?

I have a huge form (for an internal CMS) that is comprised by several sections, some of them are optional some of them are compulsory. All is under an humungous form (it has to be like this, no ajax, no other ways :-( )
Since in a Dilbertesque way everything get changed every second I was wondering if there is any simple way of grouping $_POST data, I mean sending POST like this:
$_POST['form1']['datax']
or to retrieve data from server side easily, and by easily I mean withouth having to expressily declare:
$array1 = array($_POST['datax'],$_POST['datay'],...);
$array2 = array($_POST['dataalpha'],$_POST['dataomega'],...);
since there are around 60 fields.
I hope I was able to explain this well and as always thank you very much..
If you give your input elements array-like names, they arrive in the PHP $_POST (or $_GET) array as an array:
<input type="text" name="foo[]" value="a"/>
<input type="text" name="foo[]" value="b" />
<input type="text" name="foo[]" value="c" />
<input type="text" name="foo[bar]" value="d" />
<input type="text" name="foo[baz][]" value="e" />
<input type="text" name="foo[baz][]" value="f" />
Goes to:
print_r($_POST)
foo => array (
0 => a
1 => b
2 => c
bar => d
baz => array(
0 => e
1 => f
)
)
If you name your inputs properly, you can do that. Example:
<input type="text" name="textInput[]" />
<input type="text" name="textInput[]" />
That will populate an array in $_POST named textInput. That is:
$_POST['textInput'][0] == "whatever the first was set to be"
$_POST['textInput'][1] == "whatever the second was set to be"
Using square brackets after the input name will cause it to be grouped in PHP:
<input name="foo[]" type="text" value="1" />
<input name="foo[]" type="text" value="2" />
You can also make an associative array:
<input name="foo[bar]" type="text" />
I think multi-dimensional arrays would also work, but I'm not sure if I've actually tried it.
Edit: Here's the same thing answered in the PHP FAQ.
you can use your form fields like this:
<input type="text" name="form1['datax']"/>

Categories