How can I call dynamic ISSET by multiple ID button? - php

As you can see in the picture I have multiple button inside one FORM so when I click on button It insert always the last value :: S (126).
This is my code:
<form method="post" action="" enctype="multipart/form-data">
<input type="text" class="form-control" placeholder="Numéro de chassit" name="chassit" id="chassit" >
<?php
if (mysqli_num_rows($result) > 0)
{ ?>
<?php
while($row = mysqli_fetch_array($result)) {
?>
<?php echo "<img alt='' src='../admin/image/mercedes/".$row['image']."' >";?>
<div class="card-body">
<input id="model" name="model" type="hidden" value="<?=$row['model'] ?>">
<input type="submit" name="mo" class="btn btn-secondary" value="<?=$row['model'] ?>">
</div>
</form>
And this is the process
<?php
if(ISSET($_POST['mo'])){
$demandeur = $_SESSION['username'];
$model = $_POST['model'];
$chassit = $_POST['chassit'];
$sql = "INSERT INTO tbl_xp_support (demandeur,model,chassit)
VALUES ('$demandeur','$model','$chassit')";
if (mysqli_query($con, $sql)) {
header("Location: ../xp_group.php");
} else {
echo "Error: " . $sql . " " . mysqli_error($con);
}
mysqli_close($con);
}
?>
The input name="model" it insert always the last value !!!

Because your all input fields has same name, so last one will overwrite any previous ones. If you want to select only one that was selected, you should make it as radio button:
<label class="card-body">
<input id="model" name="model" type="radio" style="display: none;" value="<?=$row['model'] ?>"/>
<input type="submit" name="mo" class="btn btn-secondary" value="<?=$row['model'] ?>">
</label>
Please note:
you never use $_POST['mo'] value that should contain selected model
You have same ID in every iteration, and that is invalid HTML

Your browser has no way to know that each submit button is supposed to be associated with a single hidden input, since they're all part of the same form. What will actually happen is that regardless of which button is pressed, all of the hidden fields will be submitted.
Since they all have the same name, but different values, PHP has to decide which value to actually put into the $_POST array. Its policy is to take the last value, which is what you see.
There are a few ways I can think of to make this work:
Put each hidden field and submit button into its own HTML <form>, rather than having one for the whole page.
Have a single hidden field at the bottom of the page, and write some JavaScript that updates that hidden field when you click a button, before submitting the form.
Look at the value of the submit button by examining the $_POST['mo'] variable, and get rid of the hidden fields completely. But beware that there are some extra cases you need to consider when doing this.

Related

PHP Get and POST data

How to I get the input id of selected button, and post it from next php page? I have this code inside my form it's dynamically populate from my database.
<?php
include('connection.php');
$query = "Select * from tblproduct where categoryID = 1 and statusProd = 1";
$result = $conn->query($query);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$id=$row["ID"];
$product=$row["product"];
$image=$row["images"];
echo '
<div class="col-sm-4 divProduct" style="outline: none;background-color: transparent;border:none;height:320px;width:300px">
<div class="content">
<input type="submit" name="btnGame" id="btnGame" class="btnSubmit" value="">
<input type="hidden" name="prodID" value="'.$id.'">
<div class="btnBuyBuy text-center">
<img src="'.$image.'" class="imgProd" style="width:200px;height:170px;">
<br><br>
<label class="nameProd">'.$product.'</label>
<br><br>
<div class="divBuy2">
<label class="lblBuy">BUY NOW</label>
</div>
</div>
</div>
</div>';
}
}
And here's my code to the next page where the id displaying.
<?php
if (isset($_POST['btnGame'])) {
$id = $_POST['prodID'];
echo "$id";
}
else{
echo "failed";
}
And the output is the last id from my tblproduct which is 13. How can I get the id of selected button?
<input type="submit" name="btnGame" id="btnGame" class="btnSubmit" value="">
<input type="hidden" name="prodID" value="'.$id.'">
You aren't trying to get the "id" (you mean value) of the button, you are trying to get the value of the hidden input next to it.
The problem with this is that proximity to the clicked submit button means nothing. All hidden inputs will be successful controls. All will be submitted to the server. Since they all share the same name, only one of them will show up in $_POST. (If you renamed them so the name ended in [] then they would all should up as an array and you still couldn't tell which was selected).
Don't use a hidden input for this.
If you care about the button that is used, then make use of the submit button.
Only the submit button used to submit the form will be successful, so its name and value can be used to tell which one was clicked.
<input type="submit" name="btnGame" id="btnGame" class="btnSubmit" value="$id">
… and then look at $_POST['btnGame'] instead of $_POST['prodID'].
Given that you have value="" I'm guessing that you don't want any text displayed on the image and that you are using CSS background image to display something in it.
Obviously, the above won't be compatible with this, so use a <button> element instead.
That allows you to have a different label and value.
It also allows you to put elements inside the label, so you can use a content image with an alt attribute instead of a background image and score a big accessibility win.
<button name="btnGame" id="btnGame" class="btnSubmit" value="$id">
<img src="/path/to/icon.png" alt="Select product number $id">
</button>

PHP get forms data with one button when the form is inside a loop fetched from database

I have a query which fetches data from the database within a loop, for each instance of loop a form is created, now I want to get the value of each forms data within the loop itself and check if it matches with its corresponding row's column in the database:
for eg:
<?php
$marks = 0;
while ($row= mysqli_fetch_assoc($resut)) {
echo '<form method="POST" action="">
<div class="col-sm-8" id="question">'.$row['question'] .'</div>
<input type="radio" placeholder="" name="answer" value = "true" id=""> True
<input type="radio" placeholder="" name="answer" value = "false" id=""> false
</form>';
if (isset($_POST['save'])){ // this is the submit button present outisde the loop at last
if ($_POST['answer'] == $row['answer']) {
$marks++;
} else {
echo "incorrect";
}
}
}
?>
<form role="form" action="" method= "POST">
<button name ="save" id=" class="btn btn-primary">Save</button>
</form>
So what I am trying to achieve is that I have a column in database which I can get by $row['answer'] within the loop. so I could check the forms data with this row by if( $_POST['answer'] == $row['answer']) .. .do smth...But the problem is that I have to keep the submit button outside the loop since there should only be only 1 submit button and if I put it outside the loop it is not working.
My attempts:
I tried to keep the form tag before the loop. if I do this then suppose there are 10 rows in database I would be needing 10 forms and 10 values taken within the loop. but then if I press the radio button in one of the rows the other would be deselected. so in my opinion the form tag should be inside the whole loop only.
I tried keeping the form submit button (present at last) inside the while loop within every instance of rows fetched. then again it would echo every button for every row which is not the motive. I just want one button for all the forms to be submitted and get values accordingly.
also I cannot do this check outside or in any other page since I have to check with every instance of the loop i.e. $row['answer'] with every instance of forms radio button data i.e. $_POST['answer'].
Thank you for every response.
If you want to send all the answers at once, you'll need to use a single form.
To do that, you can change the name of your input so that it's different for each question.
$marks = 0;
$idx = 0;
echo '<form method="POST" action="">';
while ($row= mysqli_fetch_assoc($resut)) {
++$idx;
echo
'<div class="col-sm-8" id="question">'.$row['question'].'</div>
<input type="radio" placeholder="" name="answer'.$idx.'" value = "true" id=""> True
<input type="radio" placeholder="" name="answer'.$idx.'" value = "false" id=""> False';
if (isset($_POST['save'])) { // this is the submit button present
outisde the loop at last
if ($_POST['answer'] == $row['answer']) {
$marks++;
} else {
echo "incorrect";
}
}
}
echo '</form>';
You can also inject the $idx between brackets, which will give you a single $_POST['answer'] entry, but which will be an array instead of a string. That array will contain all your answers assignated to the keys you injected as $idx :
<input type="radio" placeholder="" name="answer['.$idx.']" value = "true" id=""> True
<input type="radio" placeholder="" name="answer['.$idx.']" value = "false" id=""> False

Send value of submit button when form gets posted

I have a list of names and some buttons with product names. When one of the buttons is clicked the information of the list is sent to a PHP script, but I can't hit the submit button to send its value. How is it done?
I boiled my code down to the following:
The sending page:
<html>
<form action="buy.php" method="post">
<select name="name">
<option>John</option>
<option>Henry</option>
<select>
<input id='submit' type='submit' name='Tea' value='Tea'>
<input id='submit' type='submit' name='Coffee' value='Coffee'>
</form>
</html>
The receiving page: buy.php
<?php
$name = $_POST['name'];
$purchase = $_POST['submit'];
//here some SQL database magic happens
?>
Everything except sending the submit button value works flawlessly.
The button names are not submit, so the php $_POST['submit'] value is not set. As in isset($_POST['submit']) evaluates to false.
<html>
<form action="" method="post">
<input type="hidden" name="action" value="submit" />
<select name="name">
<option>John</option>
<option>Henry</option>
<select>
<!--
make sure all html elements that have an ID are unique and name the buttons submit
-->
<input id="tea-submit" type="submit" name="submit" value="Tea">
<input id="coffee-submit" type="submit" name="submit" value="Coffee">
</form>
</html>
<?php
if (isset($_POST['action'])) {
echo '<br />The ' . $_POST['submit'] . ' submit button was pressed<br />';
}
?>
Use this instead:
<input id='tea-submit' type='submit' name = 'submit' value = 'Tea'>
<input id='coffee-submit' type='submit' name = 'submit' value = 'Coffee'>
The initial post mentioned buttons. You can also replace the input tags with buttons.
<button type="submit" name="product" value="Tea">Tea</button>
<button type="submit" name="product" value="Coffee">Coffee</button>
The name and value attributes are required to submit the value when the form is submitted (the id attribute is not necessary in this case). The attribute type=submit specifies that clicking on this button causes the form to be submitted.
When the server is handling the submitted form, $_POST['product'] will contain the value "Tea" or "Coffee" depending on which button was clicked.
If you want you can also require the user to confirm before submitting the form (useful when you are implementing a delete button for example).
<button type="submit" name="product" value="Tea" onclick="return confirm('Are you sure you want tea?');">Tea</button>
<button type="submit" name="product" value="Coffee" onclick="return confirm('Are you sure you want coffee?');">Coffee</button>
To start, using the same ID twice is not a good idea. ID's should be unique, if you need to style elements you should use a class to apply CSS instead.
At last, you defined the name of your submit button as Tea and Coffee, but in your PHP you are using submit as index. your index should have been $_POST['Tea'] for example. that would require you to check for it being set as it only sends one , you can do that with isset().
Buy anyway , user4035 just beat me to it , his code will "fix" this for you.
Like the others said, you probably missunderstood the idea of a unique id. All I have to add is, that I do not like the idea of using "value" as the identifying property here, as it may change over time (i.e. if you want to provide multiple languages).
<input id='submit_tea' type='submit' name = 'submit_tea' value = 'Tea' />
<input id='submit_coffee' type='submit' name = 'submit_coffee' value = 'Coffee' />
and in your php script
if( array_key_exists( 'submit_tea', $_POST ) )
{
// handle tea
}
if( array_key_exists( 'submit_coffee', $_POST ) )
{
// handle coffee
}
Additionally, you can add something like if( 'POST' == $_SERVER[ 'REQUEST_METHOD' ] ) if you want to check if data was acctually posted.
You can maintain your html as it is but use this php code
<?php
$name = $_POST['name'];
$purchase1 = $_POST['Tea'];
$purchase2 =$_POST['Coffee'];
?>
You could use something like this to give your button a value:
<?php
if (isset($_POST['submit'])) {
$aSubmitVal = array_keys($_POST['submit'])[0];
echo 'The button value is: ' . $aSubmitVal;
}
?>
<form action="/" method="post">
<input id="someId" type="submit" name="submit[SomeValue]" value="Button name">
</form>
This will give you the string "SomeValue" as a result
https://i.imgur.com/28gr7Uy.gif

Grabbing specific variable from while loop for form submit

I have a while loop generating information with a checkbox, I would like to update the database with the new "completed" value. How can I select the specific checkbox that is generated. Please help with showing me how I can grab the specific value of a checkbox and the task_name.
Thanks, Ryan
while ($row = mysql_fetch_array($query)){
$task_name = $row['task_name'] ;
$task_description = $row['task_description'];
$task_completed = $row['completed'];
$tasks .= '<div id="tasksBody">
<form action="" method="post">Completed? <input name="completed" type="checkbox" '.
($task_completed == 1?'checked="checked"':'').
' /><input type="submit" value="Update"><br /><br />
<b>'.$task_name.'</b><br /><br />'.$task_description.'<hr><br /></form></div>';
}
}
echo $tasks;
You need to name your input with something unique for the row, such as the task_name, or better, a database record ID.
Then when the user submits the form, you will use $_POST["YourTaskNameOrIDHere"] to check the value.
What you have currently calls all the check boxes the same thing.
EDIT: I'm sorry, you're isolating all of these in their own forms, I just realized that.
What you can add is an <input type="hidden" value="$task_name" name="TaskName" /> to the form, so you can look what the checkbox is corresponding to. Then, when the user submits the form, use $_POST["TaskName"] to find out the name of the task.
Add a hidden field to each of your forms containing the task_id
<form action="" method="post">
Completed?
<input name="completed" type="checkbox" <?=($task_completed == 1?'checked="checked"':'')?> value="1" />
...
<input name="task_id" value="<?=$task_id"?> type="hidden" />**strong text**
</form>
After submit:
if (isset($_POST['task_id']) { // form has been submitted
$task_id = $_POST['task_id'];
$completed = $_POST['completed'];
$sql = "UPDATE task SET task_completed=$completed WHERE task_id=$task_id LIMIT 1";
// code for updating database
// better use PDO or mysqli-* instead of old and deprecated mysql_*
}

Checking Which Button was Clicked

I have a PHP generated form which consists of a list of items, each with a button next to them saying "Remove This" it outputs similar to below:
Item A - [Remove This]
Item B - [Remove This]
...
I wish to be able to click Remove This and it will detect which item it is, and then remove that from the database. Here's my code so far:
selectPlaces.php
<?php
include 'data.php';
mysql_connect($host, $user, $pass) or die ("Wrong Information");
mysql_select_db($db) or die("Wrong Database");
$result = mysql_query("SELECT * FROM reseller_addresses") or die ("Broken Query");
while($row = mysql_fetch_array($result)){
$placeName = stripslashes($row['b_name']);
$placeCode = stripslashes($row['b_code']);
$placeTown = stripslashes($row['b_town']);
$outputPlaces .= "<strong>$letter:</strong> $placeName, $placeTown, $placeCode <input type=\"button\" onclick=\"removePlace()\" value=\"Remove This\" /><br />";
}
mysql_close();
?>
Coupled with my admin.php
<div id="content" style="display:none">
Remove a Place<br><br>
<?php include 'selectPlaces.php'; echo $outputPlaces; ?>
</div>
I know I need to add some javascript to detect which button is clicked but I can't seem to get it working. I tried modifying the onclick="removePlace()" by perhaps passing a variable in the function removePlace(placeID) or something like that, but I'm new to JavaScript and I have no idea how to receive this in the removePlace function.
This seems easier to do without JavaScript. For each entry instead of generating just a button, generate a form that posts to a PHP script that does the deleting.
<form action="deletePlace.php?id=<?php echo $idOfThePlace?>">
<input type="submit" value="Remove This" />
</form>
$idOfThePlace would be the ID with you use to identify the data row.
You don't need JavaScript for that. Try running this example:
<?php var_dump($_POST); ?>
<form action="post.php" method="post">
<p>
<input type="submit" value="a" name="action" />
<input type="submit" value="b" name="action" />
</p>
</form>
You'll see that $_POST['action'] will depend on which button was pressed. For your example, you just need to set the value to identify the item that needs to be deleted. It might be useful to use the <button> element for that: <button name="delete" type="submit" value="12345">delete item 12345</button>. It'll show up as $_POST['delete'] with 12345 as value when submitted.

Categories