Multiple Forms, Wrong Value Submitted - php

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>';
}
?>

Related

How can I get the sender ID of dynamically created submit buttons?

I'm generating a html table. Each row starts with a Edit-Button.
Site A:
echo "<table border='1' align='center'>";
echo "<tr>"
. "<th style='font-weight:bold'></th>"
. "<th>".$nr.":</th>"
. "<th>Anschrift</th><th>Nachname</th>"
. "<th>Vorname</th>"
. " <th>PLZ</th>"
. "<th>Ort</th>"
. "</tr>";
echo "<form action='lxKundenEdit.php' method='POST'>";
$i=0;
foreach($arr as $key =>$value)
{
echo "<tr><td><input type='submit' name='btn'.$i.'\'' value='Bearbeiten'/></td>";
foreach($value as $subkey=>$subValue)
{
echo "<td>".$subValue."</td>";
}
echo "</tr>";
$i++;
}
echo "</form>";
echo "</table>";
Then I want to know which button has been pushed. When vardump the POST-Array it seems nothing really works. Any hints about this? regards, Ismir
Site B:
var_dump($_POST['btn0']); //f.e.
Simply pass the sender ID in a hidden input
<input type="hidden" name="sender" value="<?= $senderID; ?>">
On Site B you can then get the value from the $_POST variable:
echo $_POST['sender'];
Edit
I see I misread your question. What you can do is pass your subkey on the submit button as follows:
<input type="submit" name="submit[<?= $subkey; ?>]" value="send" />
You should give each button a unique value. When the form is posted you can then check for that value for that button.
echo '<input type="submit" name="btn'.$i.'" value="'.$i.'" />';
Edit:
As Peter pointed out in the comments, if you want to change the text of your button, you can use the button element:
<?php
echo '<form method="post">';
echo '<button type="submit" value="button 1 was used" name="button">Send</button>';
echo '<button type="submit" value="button 2 was used" name="button">Send</button>';
echo '</form>';
var_dump( $_POST[ 'button' ] );
All you need to do is:
Make array of all your submit buttons with ids as keys.
echo '<tr><td><input type="submit" name="btn[<?php echo $i;?>]" value="Bearbeiten"/></td>';
And then in PHP, get posted submit buttons like:
if (! empty($_POST['btn']) {
foreach ($_POST['btn'] as $btnId => $btnVal) {
// $btnId is Id of the button that is $i
// $btnId means button is pressed.
// $btnVal is value of the button
}
}
Just include a hidden input inside your form, eg
<input type='hidden' name='submit'/>
So you can use it to check, if the form has been sent (if(isset($_POST['submit'])) etc). Then check any other $_POST fields looking for any ['btn...'], eg
foreach($_POST as $key => $value){ // check all the $_POST fields
if(substr($key,0,3) == 'btn'){ // if its name begins with 'btn'...
$button_id = substr($key,3,NULL); // then that's some button. Get its ID
}
}
Think this should work

How to pass 2 radio selection value with a single Submit??

echo '<form method="post" action="mod_slots.php">';
$i = 1;
while(cond)
{
echo '<input type="radio" name="change1" value="'.$i.'" />';
$i++;
}
$j = 1;
while(cond)
{
echo '<input type="radio" name="change1" value="'.$j.'" />';
$j++;
}
}
echo '<input type="submit" value="Change Selected" />';
echo '</form>';
The above code passes only change1 value to the next page! But I want a single submit button, which will send both value!!??
My implementation may be wrong!
Radios with same name could only have one selection, if you want to divide them, just use different name.
Either you can pass them by giving their names as array like
echo '<input type="radio" name="change[]" value="'.$i.'" />';
and after submit you can print them like
print_r($_POST['change']);

Invalid argument when passing checkbox array from GET to POST

PHP novice here. Goal is to:
a) Display a table of booking options (fitness classes) dynamically from database records, allow user to select multiple options with checkboxes against each row - this bit's working.
b) Pass the checkbox selection to a table listing the selected data on a confirmation page. I'm getting an error here: Invalid argument supplied for foreach().
c) Update the database when user hits the second page's 'Confirm' button.
Research so far uncovered this advice on using $_GET and $_POST to achieve this with an array.
My checkbox code on the initial page:
echo '<form action="makebooking.php" method="get">';
echo '<td><input type="checkbox" name="class_id[]" value=' . $row['class_id'] . '</td></tr>';
The foreach statement error comes from this code that generates the table of choices on the second page:
//Check if the GET is set from classes.php
if (isset($_GET['class_id'])) {
// Grab the score data from the GET
foreach($_GET['class_id'] as $class_id) {
$_GET['class_id'] = $class_id;
}
}
//table header
echo '<table class="table table-bordered table-hover">';
echo '<thead><tr><th>Date</th><th>Time</th><th>Venue</th><th>Who\'s going?</th> <th>Add someone</th></tr></thead>';
//create the form
echo '<form method="post" action="' . $_SERVER['PHP_SELF'] . '">';
//Get the class IDs from the GET to use in the POST
foreach ($_GET['class_id'] as $class_id) {
$sql = "SELECT class_id, DATE_FORMAT(date, '%a, %d %b') AS new_date, DATE_FORMAT(time, '%H:%i') AS new_time, venue FROM classes WHERE class_id = '$class_id'";
$data = mysqli_query($dbc, $sql);
//---------------------------------------------------------------------------------
//get table data
while ($row = mysqli_fetch_array($data)) {
$date = $row["new_date"];
$time = $row["new_time"];
$venue = $row["venue"];
$class_id = $row["class_id"];
}
//---------------------------------------------------------------------------------
//Show a table of the selected classes
echo '<input type="hidden" name="id" value= ' . $class_id . ' />';
echo '<td>' . $date . '</td>';
echo '<td>' . $time . '</td>';
echo '<td>' . $venue . '</td>';
echo '<td>' . $username . '</td>';
echo '<td><button class="btn btn-mini" type="button"><i class="icon-user"></i><i class="icon-plus"</i></button></td></tr>';
}
echo'</table>';
// Make booking button
echo '<input type="submit" name="submit" class="btn btn-large btn-primary pull-right" value="Confirm">';
echo '</form>';
}
Full code of both pages at this pastebin. All error-fixing advice gratefully accepted!
Figured out that I had been declaring the variables in if/else loops that made them inaccessible to other parts of the code.
I also added some extra hidden input arrays into both tables to validate the input. This required a string-to-integer conversion of the class ID in order to update the db with the selected data.
Full fixed code is here for anyone struggling with something similar.

Having trouble getting submitted values and names in dynamic radio button loop

I have selected data from mysql and inserted them into a radio button form which is looped as shown:
if($num_rows) {
echo '<form name="fixtureform" method="POST" action="index.php">';
while ($row = mysql_fetch_assoc($result)) {
echo $row["home_team"] . " vs " . $row["away_team"]. '<br />' . " Home" . '<input type="radio" name="win'.$row["home_id"].'" value="'.$row["home_id"].'"/>' ." Draw" . '<input type="radio" name="'.$row["home_id"].$row["away_id"].'" value="draw"/>' ." Away" . '<input type="radio" name="win'.$row["away_id"].'" value="' . $row["away_id"] . '"/>' .'<br />';
}
echo '<input type="Submit" Name="Submitacc" Value="Submit your teams">';
echo '</form>';
} else {
echo "There are no fixtures today ";
}
I then have an if statement for submitted values:
if($_POST['Submitacc']=='Submit your teams') {
}
How would I say if the selected name of the radio button is win.$row[home_id] - insert value into mysql table. I'm struggling with the fact I can't get $row[home_id] outside of the loop?
thanks in advance
Try as below
$i=0;
while ($row = mysql_fetch_assoc($result)) {
echo $row["home_team"] . " vs " . $row["away_team"]. '<br />' . " Home" . '<input type="radio" name="result['.$i.']" value="h_'.$row["home_id"].'"/>' ." Draw" . '<input type="radio" name="result['.$i.']" value="draw"/>' ." Away" . '<input type="radio" name="result['.$i.']" value="a_' . $row["away_id"] . '"/>' .'<br />';
$i++;
}
In Your PHP
foreach($_POST['result'] as $value){
if($value == 'draw') {
//do stuff
}
else {
$apart = explode('_',$value);
if($apart[0]=='h'){
//home team win
echo $apart[1];
}
else {
//away team win
echo $apart[1];
}
}
}
use this
echo"<input name='win' type='radio' value='".$row['home_id']."' />";
Because your radios have different names they are all separate and all being submitted, I recommend naming them all "result" and giving them values of "win", "draw" and "loose" respectively.
<label>Win: <input type="radio" name="result" value="win" /></label>
<label>Draw: <input type="radio" name="result" value="draw" /></label>
<label>Loose: <input type="radio" name="result" value="loose" /></label>
<input type="hidden" name="home_team" value="<?php echo $row['home_team']; ?>" />
<input type="hidden" name="away_team" value="<?php echo $row['away_team']; ?>" />
You can access the value with $_POST['result'] and since you know the home team and away team you can handle the data accordingly
i think a diferent usage of the radio button mechanic shuold be used in this case.
in your example you are creating 3 diferent instances of a radio button for each row, instead create one instance of a radio button set with diferent values depending on the answer given
like:
<input type="radio" name="game'.$row["game_id"].'" value="'.$row["home_id"].'">
<input type="radio" name="game'.$row["game_id"].'" value="draw">
<input type="radio" name="game'.$row["game_id"].'" value="'.$row["away_id"].'">
this means that the variable $_POST["game1"] will have the value of the winner or draw that was selected for game which is game_id 1
hope this helps you
Change your element name to win.home without the id, since you will get it by the value.
Then go like:
if(isset($_POST['win.home'])) { }
Edit:
If you want to do it like this, try this:
3 radio buttons, named win.home, draw, win.away plus a unique id (mysql id?) like win.home.1234 then you can use as many games as you want. You can get the id back with explode() later.
Then the values:
1st: $row["home_id"] . "-" . $row["away_id"]
2nd: draw
3rd: $row["away_id"] . "-" . $row["home_id"]
Then when processing the form:
Split the value with explode() at the -. So the first id is always the winner.

One Form, Two Buttons To Send Info to Different Pages

I have a table being generated from PostgreSQL through PHP.
The user needs to have the option of deleting the row or updating it.
So I have successfully implemented a delete button utilizing hidden elements to pass the key information for the deletion to my delete.php
Now I am trying to add an update button which will send the php to my update.php rather than my delete.php.
However, when I open my form I tell it where to send the data upon submission.
My question then is, is there a way that I can have both buttons available and depending on which button is pressed the form posts the data to the appropriate php- delete.php vs update.php? Perhaps some attribute of input buttons I cannot think of that can direct where to POST rather than having it as a form attribute?
Here is an example of what I have:
echo '<form action="delete.php" method="POST">';
echo '<tr>';
echo '<td class="even">' . $row['id'] . '</td>';
echo '<td class="odd">' . $row['name'] . '</td>';
echo '<td class="even">' . $row['countrycode'] . '</td>';
echo '<td class="odd">' . $row['district'] . '</td>';
echo '<td class="even">' . $row['population'] . '</td>';
echo '<input type="hidden" name="todelete" value="'.$row['countrycode'].'" />';
echo '<input type="hidden" name="cityname" value='.$row['name'].'" />';
echo '<input type="hidden" name="tablename" value="'.$_POST["search-type"].'" />';
echo '<td> <input class="odd" type="submit" name="updateBtn" value="Update?" /></td>';
echo '<td> <input class="even" type="submit" name="deleteBtn" value="Delete?" /></td>';
echo '</tr>';
echo '</form>';
This is generated for each row of the table so each of the forms is unique and only that data is sent.
Let me know if you have any ideas how I can implement the two buttons!
Simplest method is to have a SINGLE script as your action, then have a basic
<?php
if (isset($_POST['deleteBtn'])) {
... do delete stuff
} else if (isset($_POST['updateBtn'])) {
... update stuff here ...
}
Otherwise you're stuck with some javascript to dynamically change the action target.

Categories