How can I loop through common fieldsets in a single form in PHP?
I have a form, which contain开发者_开发知识库s multiple virtual fieldsets.
Eg, MyForm:
Name1
Age1
Location1
Name2
Age2
Location2
Name3
Age3
Location3
Submit
If I allow the user to dynamically create more field sets on the client how can I loop through all fieldsets where name(x) is set and perform an similar action for each group, using the integer (1,2,3 etc) as a unique identifier?
I want to specify the actions once, loop through and each time change the variables used according to the number of the fieldset.
Right now, I am doing it manually for 3 hardcoded fireldsets, but it won't scale:
Pseudocode:
if($name1 is set) {
do something using $age1 and $location1
}
if($name2 is set) {
do something using $age2 and $location2
}
if($name3 is set) {
do something using $age3 and $location3
}
Thanks!
you can name your elements name="name[1]"
, name="name[2]"
and so on.
and in php do something like:
for($i=1;$i<=count($name);$i++){
// do the stuff.
}
Do it like this:
$maxIndex = 3
for(var $i=1; $i<=$maxIndex; $i++){
$name = $_POST["Name$i"];
$age = $_POST["Age$i"];
$location = $_POST["Location$i"];
//do something using $name, $age and $location
}
Hope this helps. Cheers
You should use arrays for your input fields. Then you can create any number of the following blocks:
<input name="name[]" />
<input name="age[]" />
<input name="location[]" />
In PHP you can loop through these parameters:
foreach($_POST['name'] as $key => $value) {
$name = $_POST['name'][$key];
$age = $_POST['age'][$key];
$location = $_POST['location'][$key];
}
You can use an array in php for making
In first from of fome you can use
<?php
//n is no of records u want at one time
$available = $n;
for($i=1; $i<=$available; $i++){
?>
Name <input type=hidden name="pname<?=$i?>" value=<?=$pid?>>
Age<input type=text name="age<?=$i?>" />
Location<input type=text name="age<?=$i?>" />
<?php
}
?>
in action form you can use to save these multiple recordes at one time
<?php
$available_count = $n;
for($i=1; $i<=$available_count; $i++){
$pname = "pname".$i;
$age = "age".$i;
$location = "location".$i;
$pname1 = trim($_POST[$pname]);
$age1 = trim($_POST[$pname]);
$location1 = trim($_POST[$location]);
//now you can insert these values into table/views
}
?>
Hope you will find better help...
精彩评论