Checking Which Button was Clicked - php

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.

Related

use $_GET['']; value inside $_POST[''] and submit it to the same page and display in the same page

i am new to php and while i am practing i came across a problem. actually,i have two files index1.php and index2.php. in index1.php i have a link with a unique id as
<a href="index2.php?companyid=<?php echo $row('company_id');?>>details</a>
i have got this value in index2.php as
if(isset($_GET['companyid'])){
$companyid = $_GET['companyid'];
}
now i have a search form in the index2.php as
<form method="POST" action="index2.php">
<input type="text" name="search">
<button type="submit" name="submit">submit</button>
</form>
now on button click i want the search results be displayed in the same page as
'index2.php?companyid=$companyid'
but some how if i try to use $_POST['submit']; in the same page it takes me to index2.php and instead of index2.php?companyid=$companyid and also it throws error as undefined index of $companyid if i don't use $_POST['submit']; and echo $companyid; it gives value and works fine. all i want is that to use $companyid' value inside ``$_POST['submit']; as and display the result in the same url as before
if(isset($_POST['submit']){
$companyid //throws an error index of company id
}
any help will be appreciated
First off, it looks like you are not using the company id in the form itself, so it will not be submitted as part of the the POST. You could possibly use:
<form method="POST" action="index2.php">
<?php if (isset($companyid)): ?>
<input type="hidden" name="companyid" value="<?= $companyid; ?>">
<?php endif; ?>
<input type="text" name="search">
<button type="submit" name="submit">submit</button>
</form>
But you would probably also need to change your logic to:
if(isset($_POST['companyid'])){
$companyid = $_POST['companyid'];
}else if(isset($_GET['companyid'])){
$companyid = $_GET['companyid'];
}
As Josh pointed out in the comments, PHP is not able to remember your previous GET request but this can easily be solved by altering the action attribute of the form element. By doing this you can pass on the previous data. This would look a little something like this:
<form method="POST" action="index2.php?companyid=<?php echo $companyid;?>">
<input type="text" name="search">
<button type="submit" name="submit">submit</button>
</form>
This way you will be redirected to index2.php with the URL parameters present and you will be able to retrieve both search and companyid using $_POST and $_GET or use $_REQUEST for both.

check if the radio button clicked is the answer stored in database

I am designing an online test series. I want when an answer is selected by the user, it should be validated by the answer stored in the database and move to next question on the basis of correct and incorrect choice. I am using php and mysqli. Can someone tell me how to get the id of the user selected answer and validate with the correct answer? This is html
<form method="POST" name="try" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">;
<h4> <?php echo $_SESSION["Question"] ?> </h4>
<input type="radio" name="options" value="A" id="A"> <?php echo $_SESSION["OpA"] ?> </input><br>
<input type="radio" name="options" value="B" id="B"> <?php echo $_SESSION["OpB"] ?> </input><br>
<input type="radio" name="options" value="C" id="C"> <?php echo $_SESSION["OpC"] ?> </input><br>
<input type="radio" name="options" value="D" id="D"> <?php echo $_SESSION["OpD"] ?> </input><br>
<input type="radio" name="options" value="E" id="E"> <?php echo $_SESSION["OpE"] ?> </input><br>
<button type="button" class="btn" name="submit" value="submit" >Submit</button>
<?php
$conn = mysqli_connect($servername, $username, $password);
mysqli_select_db( $conn , 'myDB' );
echo "<form method='get' action=" .htmlspecialchars($_SERVER['PHP_SELF']) . ";>";
$sql = "SELECT * FROM QUANT_MEDIUM ORDER BY RAND() LIMIT 1";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
while($row = $result->fetch_assoc())
{
$_SESSION['ans'] = $row['Correct'];
$_SESSION['Question'] = $row['Ques'];
$_SESSION['OpA'] = $row['Option_A'];
$_SESSION['OpB'] = $row['Option_B'];
$_SESSION['OpC'] = $row['Option_C'];
$_SESSION['OpD'] = $row['Option_D'];
$_SESSION['OpE'] = $row['Option_E'];
}
}
?>
<?php
if (isset($_POST['submit']) and ! empty($_POST['submit']))
{
if (isset($_POST['options']))
{
$radio_input = $_POST['options'];
echo $radio_input;
}
}
else
{
echo "wrong";
}
?>
Before looking at a possible solution you must determine where you want the check to be done. You tagged the question "jquery" so I guess you're interested in a clientside option as well as a serverside option.
Client side
If you want to do the check clientside, depending on how you implement it, the user might be able to see the correct answer by inspecting the code. If this is no problem, you can have the fastest user experience by checking it clientside.
The most simple option, but easy to "hack" would be to add an extra attribute to the radiobutton. Something like "correct" or so. When the submit button is clicked you can use jquery to check if the selected radio button has the "correct" attribute and do whatever action you want with that info.
You can also have the frontend do a query to the server to check. This would be more secure, but the method described above is the simplest.
Server side
If you want the client to have no possible way of getting the answer beforehand, you're best doing the check serverside. Here the "onclick"you have on the submit button can be removed and have the form do an actual post to the server, and have the server do a check and display the next question if the given answer is correct.
In order to have the server know what question is being checked you could add a hidden field with the question ID.
The validation can be done on the server side using php. The solution would be not to use a submit button and let the server take the responsibility of checking what is submitted to the server. So the submit button can be replaced by the following :
<input type="submit" name="submit" value="submit" class="btn"></input>
And the validation can be done using the following piece of code :
<?php
if (isset($_POST['submit']) and ! empty($_POST['submit']))
{
if (isset($_POST['options']))
{
$radio_input = $_POST['options'];
//echo $radio_input;
if($radio_input == $_SESSION['ans'])
echo "correct";
else
echo "incorrect";
}
}
?>

Returning only the last value of query

This is my second code but the problem is I have 3 queries. So it only returns the last product_id when i Click update it always return product_id=3, but i want update the product_id=2
<form action="update_qty.php" method="POST">
<?php while($getorder = mysqli_fetch_array($order)){ ?>
<input type="hidden" value="<?=$getorder['price']?>" name="actual_price">
<input type="hidden" value="<?=$getorder['product_id']?>" name="product">
<input type="text" value="<?=$getorder['qty']?>" name="qty" size="1" style="text-align:center">
<input type="submit" value="update" name="update">
<?php } ?>
</form>
Your problem is that the PHP is server side and you need something client side to read the value of the text box. You would need a page refresh to pass the text field value to the server so it could write it to the url in the anchor tag. Which is what the form submit would do, but as it would have submitted the value already the anchor tag would be pointless
To do it without a page refresh use Javascript. It would be easy to do with jQuery. You could add an event that writes whatever is entered in the text box the the anchor tags href as it is typed.
I'll do something more like this.
One form per product.In your case when you submit the form the qty value will always be the las found.
<?php while($getorder = mysqli_fetch_array($order)){ ?>
<form action="update_qty.php" method="POST">
<input type="hidden" value="<?=$getorder['price']?>" name="actual_price">
<input type="hidden" value="<?=$getorder['product_id']?>" name="product">
<input type="text" value="<?=$getorder['qty']?>" name="qty" size="1" style="text-align:center">
<input type="submit" value="update" name="update">
</form>
<?php } ?>
You can add more information like this
update
You can not get all values as like that because input name overwrite in every loop iteration.
For multiple values you can try in two ways like:
<?php
while($getorder = mysqli_fetch_array($order)){
$newArr[] = $getorder['price']."~".$getorder['product_id']."~". $ getorder['qty'];
} //while end
?>
<input type="hidden" name="allinputs" value="<?=$newArr?>">
Input field outside the loop.
In php explode array value with ~ and get the all values.
Other solution is that
Your input field name must be change like:
<?php while($getorder = mysqli_fetch_array($order)){ ?>
<input type="hidden" value="<?=$getorder['price']?>" name="actual_price_<?=$getorder['product_id']?>">
<?php } ?>
Change field name in every iteration.
In current scenario either you need three different buttons or the best solution to use AJAX request .
update
On update_qty.php u can use like this
<?php echo $_GET['product_id'];?>

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

DELETE FROM table WHERE ID='$id' — Variable refuses to stick

Trying to perform a very simple task here.
I have an <ol> that contains 4 rows of data in some handy <li>s. I want to add a delete button to remove the row from the table. The script in delete.php appears to have finished, but the row is never removed when I go back and check dashboard.php and PHPMyAdmin for the listing.
Here's the code for the delete button (inside PHP):
Print "<form action=delete.php method=POST><input name=".$info['ID']." type=hidden><input type=submit name=submit value=Remove></form>";
Moving on to delete.php:
<?
//initilize PHP
if($_POST['submit']) //If submit is hit
{
//then connect as user
//change user and password to your mySQL name and password
mysql_connect("mysql.***.com","***","***") or die(mysql_error());
//select which database you want to edit
mysql_select_db("shpdb") or die(mysql_error());
//convert all the posts to variables:
$id = $_POST['ID'];
$result=mysql_query("DELETE FROM savannah WHERE ID='$id'") or die(mysql_error());
//confirm
echo "Patient removed. <a href=dashboard.php>Return to Dashboard</a>";
}
?>
Database is: shpdb
Table is: savannah
Ideas?
It's refusing to stick because you're calling it one thing and getting it with another. Change:
"<input name=".$info['ID']." type=hidden>"
to
"<input name=ID value=".$info['ID']." type=hidden>"
because in delete.php you're trying to access it with:
$id = $_POST['ID'];
You should really quote attribute values as well ie:
print <<<END
form action="delete.php" method="post">
<input type="hidden" name="ID" value="$info[ID]">
<input type="submit" name="submit" value="Remove">
</form>
END;
or even:
?>
form action="delete.php" method="post">
<input type="hidden" name="ID" value="<?php echo $info['ID'] ?>">
<input type="submit" name="submit" value="Remove">
</form>
<?
Please, for the love of the web, don't built an SQL query yourself. Use PDO.
Just another point I'd like to make. I'm 95% sure that you can't give an input a numeric name/id attribute. It has to be like "id_1" not "1".
Also with php you can do arrays.
So you could do this
<input name="delete[2]">
then in your php
if(isset($_POST['delete']))
foreach($_POST['delete'] as $key=>$val)
if($_POST['delete'][$key]) delete from table where id = $val

Categories