Reputation: 633
I have a page with two section(forms), first is about number of how many new fields I want to create and second - where are the new fields. So my problem is that I can't get the information from second fields. Here is the code:
echo "<form action='create-table.php' method='post'>";
echo "How much fields you want?: <input type='numer' name='fieldsnum'><br>";
echo "<input type='submit' name='first'>";
echo "</form>";
$fieldsnum = $_POST["fieldsnum"];
echo "<form action='create-table.php' method='post'>";
echo "Table Name: <input type='text' name='table'><br><br>";
$table = $_POST["table"];
echo $table;
while ($a < $fieldsnum){
echo "Table Field $a: <input type='text' name='$a'><br>";
$a++;
}
echo "<input type='submit' name='second'>";
echo "</form>";
for($a = 0; $a<$fieldsnum; $a++){
$info[$a] = $_POST[$a];
}
First loop work correctly, but the second has some problem and it can't get the data. I don't understand PHP and I am sorry if it has a lot of mistakes or bad practices.
Upvotes: 1
Views: 76
Reputation: 8171
There are two things wrong here:
First, you need to set $a = 0;
before your while
loop, otherwise the first iteration of
while ($a < $fieldsnum){...}
Will output:
<input type="text" name>
So you will get no data from that field.
Secondly, Your for
loop fails because $fieldsnum
is empty on the second submission.
Try this:
<?php
$fieldsnum = $_POST["fieldsnum"];
$table = $_POST["table"];
if (isset($_POST["fieldsnum_keep"])) {
$fieldsnum = $_POST["fieldsnum_keep"];
for($a = 0; $a < $fieldsnum; $a++){
$fieldName = $_POST["feild_$a"];
echo "Field Name $a : $fieldName <br>";
}
}
?>
<form action='create-table.php' method='post'>
How much fields you want?
<input type='number' name='fieldsnum'><br>
Table Name:
<input type='text' name='table'><br>
<?php
echo $table . "<br>";
$a = 0;
while ($a < $fieldsnum){
echo "Field Name $a: <input type='text' name='feild_$a'><br>";
echo "<input type='hidden' name='fieldsnum_keep' value='$fieldsnum'><br>";
$a++;
}
?>
<input type="submit" name="second" value="Submit">
</form>
I have kept the value of $fieldsnum
by adding it to a hidden field and then using it later in the for loop. I have also made it only one form, which will by submitted twice, instead of 2 forms.
Upvotes: 1