Sorry for the noob question. But I am stuck here.
This is my HTML form where the user-form div can be cloned to as many as possible. The #submit-form div has some hidden values which are common for all.
HTML -
<div class="user-form">
<input type="text" autocomplete="off" name="name[]" >
<input type="email" autocomplete="off" name="mail[]" >
</div>
<div class="user-form">
<input type="text" autocomplete="off" name="name[]" >
<input type="email" autocomplete="off" name="mail[]" >
</div>
<div id="submit-form">
<input type='hidden' name='refer_user_id' value='<?php echo $refer_user_id ?>'>
<input type='hidden' name='refer_user_email' value='<?php echo $refer_user_email ?>'>
<input type="submit" value="Invite" />
<input type="button" class="button" id="clonetrigger" value="Clone" />
</div>
I'm using ajax to submit the form. Basically I want to create accounts using the name and email fields. In PHP How do I use foreach to loop through the name and email fields so that I can create unique accounts?
My print_r($_POST); array looks like this.
Array
(
[name] => Array
(
[0] => david
[1] => Mark
[2] => cindy
)
[mail] => Array
(
[0] => david#abc.com
[1] => mark#abc.com
[2] => cindy#abc.com
)
[refer_user_id] => 2
[$refer_user_email] => test#abc.com
)
Create a loop with a number of iterations equal to the number of submitted name/email pairs, then use the loop counter to access the values for each user.
for ($i = 0; $i < count($_POST['name']); $i++) {
{
$name = $_POST['name'][$i];
$mail = $_POST['mail'][$i];
// Process the new user
}
go through one of the arrays with a foreach, use the key for the second array.
foreach($_POST['name'] as $key =>$name ){
$mail = $_POST[$key];
}
foreach($_POST['name'] as $key => $val) {
echo $val
}
foreach($_POST['mail'] as $key => $val) {
echo $val
}
Easiest way to loop through those elements. You can reference the other elements with $_POST['refer_user_id']. While this works for the purposes of a foreach, the for loop posted above is more efficient, so I'd recommend using it.
http://php.net/manual/en/control-structures.foreach.php More reading on it here.
You can use array_combine function:
$data = array_combine($_POST['name'],$_POST['mail']);
foreach($data as $name=>$mail){
print $name;
//...
}
See array_combine.
You could also use the JavaScript that's auto-generating the form items to give them a name that would result in linking the php object. i.e.
<div class="user-form">
<input type="text" autocomplete="off" name="user[1][name]" />
<input type="email" autocomplete="off" name="user[1][mail]" />
</div>
<div class="user-form">
<input type="text" autocomplete="off" name="user[2][name]" />
<input type="email" autocomplete="off" name="user[2][mail]" />
</div>
Then you could loop through the pairs with foreach($_POST['user'] as $key=>$value) etc...
Related
I have multiple inputs in a file like this:
<form action="card_generate.php">
<input type="text" name="tZero">
<input type="text" name="tOne">
<input type="text" name="tTwo">
<input type="text" name="tThree">
</form>
in the file card_generate.php this have to go in an array i have wrote:
$tabs = array($_POST["tZero"], $_POST["tOne"], $_POST["tTwo"], $_POST["tThree"]);
Is there a way I can put these values in an array through a loop or something instead of putting each value in an array one by one, there can be more values than four values.
Use input name array,
<form action="card_generate.php">
<input type="text" name="t[]">
<input type="text" name="t[]">
<input type="text" name="t[]">
<input type="text" name="t[]">
</form>
And, you will get in post,
print_r($_POST['t']);
You can also use a foreach loop as shown in the example:
HTML
<form method="POST">
<input type="text" name="tZero">
<input type="text" name="tOne">
<input type="text" name="tTwo">
<input type="text" name="tThree">
<input type="submit" name="">
</form>
PHP
<?php
if ( isset($_POST) ) {
foreach ($_POST as $key => $value) {
echo "Name: $key, value: $value";
echo "<br>";
}
}
?>
RESULT
Name: tZero, value: first
Name: tOne, value: hi
Name: tTwo, value: firthfds
Name: tThree, value: fourth value
P.S. Don't forget method="POST" in your <form>.
You can, using array_push: http://php.net/manual/de/function.array-push.php
You can than just loop like this:
for($i = 0; $i < 10; $i++) {
if(isset($_POST["t" . $i])) {
array_push($array, $_POST["t" . $i]);
}
}
I generate a dynamic quantity of form inputs, based on a user-submitted number ($transponum).
I use str_repeat to build a string containing the desired number of inputs.
But I'm having trouble naming the inputs. I need:
<input type="text" name="transpo(a number that increases every repeat)" />
How can I achieve that with PHP?
Here is my code:
<form id="form" name="form" method="post" action="step8.php" role="form">
<div class="form-group"><?php
$a = 1;
$str.= "<label class=\"control-label\" for=\"exampleInputEmail1\">Name</label>";
$str.= "<input style=\"width: 60%;\" type=\"text\" class=\"form-control\" id=\"transponum\" name=\"transponame".$a."\" placeholder=\"Name\">";
$str.= "<label class=\"control-label\" for=\"exampleInputEmail1\">ID</label>";
$str.= "<input style=\"width: 60%;\" type=\"text\" class=\"form-control\" id=\"transponum\" name=\"transpoid".$a."\" placeholder=\"Name\"><hr>";
$str.= $a = $a+1;
echo str_repeat($str, $transponum);
?></div>
<button type="submit" class="btn-success btn" name="submit">Next</button>
</form>
I have several suggestions, detailed below:
Use a loop
Use a for loop rather than str_repeat.
Use the loop to increment your $a variable from 1 to $transponum.
for ($a=1;$a<=$transponum;$a++) { ... }
Post as arrays
Name your inputs so that they post as arrays. That way, you don't need to dynamically build the input names.
<input name="names[]" />
<input name="ids[]" />
Notice the square brackets after the variable name, that's what makes it an array. You can group the elements into different arrays by assigning the same name to different elements.
-- FAQ # php.net
Then, you'll end up with a $_POST array like this:
Array
(
[names] => Array
(
[0] => 'name 1',
[1] => 'name 2',
[2] => 'name 3',
...
),
[ids] => Array
(
[0] => 'id 1',
[1] => 'id 2',
[2] => 'id 3',
...
)
)
Remove duplicated IDs
Element IDs must be unique. Associate labels with inputs implicitly by placing the <input> elements inside their respective <label> elements. Then you can remove the duplicated IDs.
To associate a label with another control implicitly, the control element must be within the contents of the LABEL element. -- forms # w3.org
<label>Name: <input /></label>
Also see this simple label example at developer.mozilla.org, for reference.
Complete Example
Here's an example that includes all of my suggestions:
<form id="form" name="form" method="post" action="step8.php" role="form">
<div class="form-group"> <?php
for ($a=1;$a<=$transponum;$a++) {
?><label>
<span>Name</span>
<input type="text" name="transponame[<?=$a?>]" placeholder="Name">
</label>
<label>
<span>ID</span>
<input type="text" name="transpoid[<?=$a?>]" placeholder="Name">
</label>
<hr><?php
}
?></div>
<button type="submit" class="btn-success btn" name="submit">Next</button>
</form>
Edit:
Note that specifying the $a value in input names is probably not necessary. In your context, empty brackets will work just as well:
<input type="text" name="transponame[]" placeholder="Name">
Specifying array keys is optional in HTML. If you do not specify the keys, the array gets filled in the order the elements appear in the form. -- FAQ # php.net
To add to showdev's answer.
You cannot use str_repeat to achieve what you have in mind. str_repeat literally repeats a string. See the documentation page.
In your case, you have to use either a loop or create array type input names.
Make sure you don't use duplicate Ids
<form id="form" name="form" method="post" action="step8.php" role="form">
<div class="form-group">
<?php for($i=0;$i<transponum;$i++){ ?>
<label class="control-label" for="exampleInputEmail1">Name</label>";
<input style="width: 60%;" type="text" class="form-control" id="transponum" name="transponame<?php echo $i;?>" placeholder="Name">
<label class="control-label" for="exampleInputEmail1">ID</label>
<input style="width: 60%;" type="text" class="form-control" id="transponumLabel" name="transpoid<?php echo $i;?>" placeholder="Name"><hr>
<?php } ?>
</div>
<button type="submit" class="btn-success btn" name="submit">Next</button>
</form>
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
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;
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.