PHP $_POST from dynamically generated form - php

I am creating a form based on a user selection of $node_number ... so the form looks like:
function createForm($node_number) {
echo "<form id=\"form\" name=\"form\" action=\"molecule_display.php\" method=\"post\">";
for ($n = 1; $n <= $node_number; $n++) {
echo "<fieldset class=\"step\">
<input id=\"node_title" . $n . "\" name=\"node_title" . $n . "\" />
<input id=\"node_comment" . $n . "\" name=\"node_comment" . $n . "\" type=\"textarea\" />
</fieldset>";
}
echo "<input type=\"hidden\" name=\"node_number\" value=\"" . $node_number . "\">
<button id=\"submit_node\" type=\"submit\">Submit</button>"
echo "</form>";
}
Which will create $node_number of versions of that form element. My question is how to dynamically name the form elements to be able to manage them easier when I am processing them. The way I'm doing it right now, by adding the $n iterator to the name attribute is not ideal I think.
I understand that I can declare the name="" attribute as an array like name[]="" ... in terms of giving each sub-element of the larger form a unique name.
I'm guessing I want a multi-dimensional array of the individual form segment ... just not sure how to best handle those within a form and within the $_POST variable.
Does anyone have any suggestions?

I think you can do it this way:
function createForm($node_number) {
echo '<form id="form" name="form" action="molecule_display.php" method="post">';
for ($n = 1; $n <= $node_number; $n++) {
echo '<fieldset class="step">
<input id="node_title'.$n.'" name="nodes['.$n.'][node_title]" />
<input id="node_comment'.$n.'" name="nodes['.$n.'][node_comment]" type="textarea" />
<button id="submit_node" type="submit">Submit</button></p>
</fieldset>';
}
echo '</form>';
}
And then get $_POST['nodes'] which will be multidimensional array, which you can iterate with foreach. You will get $_POST['nodes'][1] = array('node_title'=>... , 'node_comment'=>...); and so on.

If you use the array like you were saying in your post you should be able to access them pretty easily.
function createForm($node_number) {
echo "<form id=\"form\" name=\"form\" action=\"molecule_display.php\" method=\"post\">";
for ($n = 1; $n <= $node_number; $n++) {
echo "<fieldset class=\"step\">
<input id=\"node_title_" . $n . "\" name=\"node_title[" . $n . "]\" />
<input id=\"node_comment_" . $n . "\" name=\"node_comment[" . $n . "]\" type=\"textarea\" />
<button name=\"submit_node[" . $n . "]\" type=\"submit\">Submit</button></p>
</fieldset>";
}
echo "</form>";
}
I also changed the submit_node to a name and gave it an array value because an ID must be unique, which will cause errors if you are referencing it somewhere.
You could loop through the results like this:
foreach ($_POST['node_title'] as $key => $response) {
$title = $response;
$comment = (!empty($_POST['node_comment'][$key])) ? $_POST['node_comment'][$key] : "";
// Save title / comment here.
}

Since every form has its own submit button, nothing stops you from using name="node_title" in all of them. If you now add <input type="hidden" name="index" value="$n"> and read this first, your logic becomes very easy.

Related

Multiple Forms, Wrong Value Submitted

I have PHP code creating multiple forms on a single page and the submission of any of these forms should trigger an API call based on which form was submitted.
if(isset($_POST['pickApples'])) {
echo '<h1>Picking Apple ' . $_POST['appleId'] . '</h1>';
// Function that calls API
pickApple($_POST['appleId']);
}
// $listOfApples is a list of 10 apples each with a unique ID
foreach ($listOfApples as $apple) {
echo '<form method="post" action="mypage.php">';
echo '<input type="hidden" name="appleId" value="' . $apple->{"id"} . '">';
echo '<button type="submit" class="my-button-class" value="click" name="pickApples">Pick Me</button>';
echo '</form>';
}
No matter which of the form buttons I click, the value in $_POST['appleId'] is the ID of the first apple in the list. I don't have much experience with PHP or HTML forms, is my approach completely off?
I am seeing some small mistakes as
echo '<input type="hidden" name="appleId" value"' . $apple->{"id"} . '">';
You should fix it,instead of foreach yor can use for loop to display forms,
as I haven't $listofapples,I used 10,you can query for row numbers than place row numbers value as $listofapples,then echo your unique id to input value,
Finally it's working as you wished
Check it & let me know if it's the perfect fit for you
<?php
if(isset($_POST['pickApples'])) {
echo '<h1>Picking Apple ' . $_POST['appleId'] . '</h1>';
// Function that calls API
pickApple($_POST['appleId']);
}
$listOfApples = 10;
// $listOfApples is a list of 10 apples each with a unique ID
$sn=0;
for ($i = 1; $i <= $listOfApples; $i++) {
echo '<form method="post" action="hy.php">';
echo '<input type="hidden" name="appleId" value=" ' .++$sn. '"/>';
echo '<button type="submit" class="my-button-class" value="click" name="pickApples">Pick Me</button>';
echo '</form>';
}
?>

How to store POST values for each form in an array?

Basically the code is supposed to be simple yet it is not working!
First page:
<?php
$i = 1;
$var;
while($i != 10)
{
$var="
<form id='upload' action='test2.php' method='POST'>
<input type='hidden' name='test' value='{$i}'>
<input class='buttom' name='album' id='submit' value='Go to album' type='submit'>
</div> ";
$i = $i+1;
echo $var;
}
?>
Second page:
<?php
echo $_POST['test'];
?>
when I run the code I always get the last value only (9) ... I need to have different value for each button .. can you help me?
You don't need multiple forms or hidden inputs to achieve this. You can just use buttons, and set their values to $i.
echo "<form id='upload' action='test2.php' method='POST'>";
for ($i = 0; $i < 10; $i++) {
echo "<button type='submit' name='test' value='$i'>Go to album</button>";
}
echo '</form>';
In test2.php, $_POST['test'] will have the $i value of the button you clicked.
Create single form with multiple input elements name as an array to get multiple value's in single input
Try this:
<input type='hidden' name='test[]' value='{$i}'>
Now you will receive an array of test as $_POST['test'] with different values
The problem with the other proposed solution is that you will have 10 forms, but you won't be able to submit all of the items at once. You will only be able to submit the value of one of them.
I believe you're trying to create 10 input elements instead of 10 separate forms:
<?php
$i = 1;
$var;
$var .= "<form id='upload' action='test2.php' method='POST'>"
while($i != 10)
{
$var .= "<input type='hidden' name='test[]' value='{$i}'>"
$i = $i+1;
}
$var .= "<input class='buttom' name='album' id='submit' value='Go to album' type='submit'>
</div>"
echo $var
?>
Here's code that I would suggest instead of what you've got:
<?php
$html = "<form id='upload' action='test2.php' method='POST'>";
for ($i = 1; $i <= 10; $i++){
$html .= "<input type='hidden' name='test[]' value='{$i}'>";
}
$html .= "<input class='buttom' name='album' id='submit' value='Go to album' type='submit'>"
$html .= "</form>";
echo $html
?>
It's a little more work than what Mahesh's answer would require
First, a question: do you really want 10 forms - or do you want one form with 10 questions. Keep in mind that $_POST will only contain values from the form which was submitted (read: one form).
I think you want something like
<form id="upload" action="test2.php" method="POST">
<?php for ($i = 0; $i < 10; $i++) { ?>
<input name="test[]" type="hidden" value="<?=$i?>">
<?php } ?>
<button type="submit">submit</button>
</form>
edit: given your response below, why not use query parameters?
Go to Album <?=$i?>

Pass Additional Variable in Option Selected form

I have a loop that creates options in a drop down form.
How can I pass the variable $objectID[$i] from the loop where $i consistent with the selected value $i
echo '<form action="#" method="post"><select name="Restaurant">';
for ($i = 0; $i < count($restaurants); $i++){
$name[$i] = $restaurants[$i]->get("Name");
$city[$i] = $restaurants[$i]->get("City");
$objectID[$i] = $restaurants[$i]->getObjectID();
//echo '<input type="hidden" name="passRestaurant" value="' . $name[$i]. '" />'; // tried this, but it just messes up the format of the drop down
echo "<option>{$name[$i]} -" . " {$city[$i]}</option>";
}
echo '</select><br><br><input type="submit" name="submit" value="Next" />
</form>';
}
This prints the value that was selected, but I also want to print the $objectID[$i] at the same $i value:
if(isset($_POST['submit'])){
$selected_val = $_POST['Restaurant']; // Storing Selected Value In Variable
echo "You have selected :" .$selected_val; // Displaying Selected Value
}
why you just put $objectID[$i] in
echo "<option value=\"{$objectID[$i]}\">{$name[$i]} - {$city[$i]}</option>";
so you can get all the properties of Restaurant with $objectID

Display variable with auto-increment

I have a form that records various fields with a variable name in autoincrement.
when I save my my form variables looks like
<form>
<?php
$i = 1;
foreach ($variables as $var ) {
echo '<input type="text" name="txt$i" value="$var->name" />';
$i ++;
}
?>
</form>
And my question is how to display the value of the input field, i make that, but not working
<?php
foreach ($variables as $var) {
echo $var->txt$i;
$i ++;
}
?>
There are couple of bugs in both of your scripts. Here they are fixed.
<form>
<?php
$i = 1;
foreach ($variables as $var ) {
echo '<input type="text" name="txt' . $i . '" value="' . $var->name . '" />';
$i++;
}
?>
</form>
<?php
$i = 1;
foreach ($variables as $var) {
echo $var->{"txt" . $i};
$i++;
}
?>
In PHP, single-quoted strings do not allow for variable interpolation.
Try:
echo '<input type="text" name="txt' . $i . '" value="' . $var->name . '" />';
This is happening because you are using single quotes:
echo '<input type="text" name="txt$i" value="$var->name" />';
and inside single quotes variable interpolation does not happen.
Instead use:
echo '<input type="text" name="txt'.$i.'" value="'.$var->name.'" />';
This should work,
<form>
<?php
$variables = array("red","yellow","blue","orange","green");
$i = 1;
foreach ($variables as $var ) {
$name = "txt".$i;
echo "<input type='text' name='".$name."' value='".$var."' />";
$i++;
} ?>
</form>
You need to put variables in double quotes, i thought it would be easier to create a name variable and concatenate the incremented value on to the end of it
Can't get what you want from your question.
May be just
echo $txt.$i;
?

How to display the selected data from this form?

So this is part of my code :
echo "<form name='whatever' action='next.php' method='get'>";
while($row = mysql_fetch_assoc($qsq))
{
echo"<input type='checkbox' name='choice[]' value='" . $row['question_id'] . "' /> ". `$row['question_text'] . '<br />';`
}
echo"<br>";
echo "<input type='submit' value='submit' /></form>";
What should i do in the next.php ? I'm thinking to put the selected info in an array and display it. Then store the selected results in a table.But i am not sure with the codes.I am beginner in php can someone help me with the coding ?Thanks in advance!
First of all I cleaned up your code a little bit. (Using single quoutes around HTML trributes is uncanny).
echo ('<form name="whatever" action="next.php" method="get">');
while ($row = mysql_fetch_assoc ($qsq)) {
echo ('<input type="checkbox" name="choice[' . $row["question_id"] . ']" value="1" /> ' . $row["question_text"] . '<br />';
}
echo '<br />';
echo '<input type="submit" value="submit" /></form>';
Then you can iterate thru the values with a foreach loop in next.php.
echo ('<ul>');
foreach ($_GET["choice"] as $key => $value){
echo ('<li>' . $key . ' is ticked</li>');
}
echo ('</ul>');
Note that the array's keys hold the real information here,values wil only contain the number 1.
Take a look ath the source of resulting HTML. This is not theonly possible solution but good for learning purposes.

Categories