PHP Multiple Submit Buttons in table - php

I have been creting a php website that allows users to add comments to an image that is within the system.
The way my code currently works is that it gets all of the comments for that image and places them into a table using a while loop:
$commResult = mysql_query("SELECT u.userID, u.USERNAME, c.COMMENT, c.DATE_ADDED, c.ACTIVE, c.id FROM USERS u, COMMENTS c WHERE u.id = c.user_id and c.box_id = $boxId ORDER BY c.DATE_ADDED DESC");
while ($row = mysql_fetch_array($commResult))
{
if ($row[4] != 0)
{
echo "<tr><td><a href='User.php?uid=$row[0]'>$row[1]</a></td>";
echo "<td style='text-align:right;'>" . date("d M y g:iA", strtotime($row[3])) ;
if (isLoggedIn())
echo " - DELETE";
echo "</td></tr>";
echo "<tr><td colspan='2'>" . $row[2] . "</td></tr>";
}
}
The problem i am having is that i would like to put a submit button where the word DELETE is. This would create a button for each comment row and therefore if clicked the code would not know what button has been pressed. Is there anyway to get arround this so each button has a individual ID so when the code is submitted it knows what the id of the comment is and therefore i am able to process a delete on the database table for that comment ID.
I have tried adding this piece of code where the word DELETE is:
if (isLoggedIn())
echo " - <button type='submit' name='delCom_sub' value='$row[5]' >X</button>";
However when i try to handle the button click using the following code:
if (!empty($_POST['delCom_sub']))
{
echo "test";
}
IF i click a button the word "test" is never displayed.

It can be done with a separate form for each comment row. The ID of the comment is stored in a hidden field. Using this method you need to remove any parent form to prevent nested forms.
if (isLoggedIn())
{
echo '<form action="delete.php" method="post">
<input type="hidden" name="id" value="' . (int)$row['id'] . '" />
<input type="submit" value="Delete" />
</form>';
}
On the page that you post to, ie delete.php:
if(isset($_POST['id']) && isLoggedIn())
{
// do the delete with $_POST['id']
}
Other than that, you could do it with Javascript by populating a hidden field when a button is clicked. Another option would be to store the comment ID in a submit button's name attribute, doing that you would have to loop over the post variables and parse out the ID.
Example using the button name:
if (isLoggedIn())
echo " - <input type='submit' name='delete_" . (int)$row['id'] . "' value='Delete' />";
On the receiving page:
if($_SERVER['REQUEST_METHOD'] == 'POST' && isLoggedIn())
{
foreach($_POST as $key => $value)
{
if(strpos($key, 'delete_') === 0)
{
$id = substr($key, 7);
// do the delete for $id
}
}
}

Related

PHP POST value from <input> that was created with While loop

I am attempting to create a page that displays buttons that are associated to an account number that is a primary key in a database. When I click on the button I want that button to take its value and assign it to a variable that can be used for loading information into a profile page that will load after the button click.
After the button click I would like to load a profile page that uses the value (acc_ID) to load each of the profile attributes (name, location, etc) from a database. I have the functionality to do this already because I have it set up for when a user logs in they see their information populate in their profile page.
So far I have a While loop that populates a table with all of the player account numbers and "View Profile" buttons. Each button is assigned the player account number as a value and is also part of the name.
$query = "SELECT * FROM player";
$result = mysqli_query($conn, $query);
echo "<table>
<tr>
<th>View Profile</th>
<th>Acct Id</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo" <form action='php/createPlayerProfilesList.php'>";
echo "<tr>";
echo"<td> <input type='submit' name='submit-'.$row[acc_ID].'' value='View
Profile - $row[acc_ID]'> </input> </td>";
echo "<td class='viewProfile'><input name='player[]' class='getPlayerId'
readonly type='text' value='". $row['acc_ID'] ."' > " . $row['acc_ID'] . "
</input></td>";
echo "<td>" . $row['player_FName'] . "</td>";
echo "<td>" . $row['player_LName'] . "</td>";
echo "</tr>";
echo "</form>";
}
echo "</table>";
What I can't figure out is how to display the players profile information into a profile template after I click on their specific View Profile button which takes me to the profile.php template. I know how to load the information into the profile template based on acc_ID because it does that when they login but I can't figure this one out.
This is a sample of the profile code that populates the template based on what acc_ID is the SESSION variable.
session_start();
include("navbarphp.php");
if($_SESSION['person_type'] == 'P'){
$acct_ID = $_SESSION['acc_ID'];
$query = "SELECT * FROM player WHERE acc_ID = '$acct_ID'";
$result = mysqli_query($conn, $query);
while($row = $result->fetch_assoc()){
$location = $row['player_location'];
$fname = $row['player_FName'];
$lname = $row['player_LName'];
$school = $row['high_school'];
$gpa = $row['GPA'];
$bio = $row['BIO'];
$pos = $row['position'];
}
}
I searched for a good while on this site and had a couple things that helped but in the end I still am not able to pass a specific View Profile button value. Any help would be great. Thanks
You may have better luck by adjusting your html output to the following format:
while($row = mysqli_fetch_array($result))
{
echo '<tr>';
echo '<td><form action="php/createPlayerProfilesList.php">';
echo '<input type="hidden" name="playerId" value="'. $row['acc_ID'] .'">';
echo '<input type="submit" name="submit" value="View Profile - '. $row['acc_ID'] .'">';
echo '</form></td>';
echo '<td>'. $row['player_FName'] .'</td>';
echo '<td>'. $row['player_LName'] .'</td>';
echo '</tr>';
}
What this does is pull the form element inside a table cell, because where you have it now, wraps a table row (which is bad html). Then you put the acc_ID into a hidden input field, which is what you would use to pull the data.
In your createPlayerProfilesList.php script you would use it like this:
<?php
if (!empty($_POST['playerId'])) {
// ... pull from db based on value in $_POST['playerId']
$acct_ID = (int)$_POST['playerId'];
// ...
}
?>
This is of course a shortened example of one of the ways you could go about doing this. For example another method used these days, is by styling elements and using javascript with ajax to pull a 'record' of data, to then display dynamically in a box or overlay on the page when you click a button to 'view more'. However that example would go beyond the scope of this question ;)

How to handle multiple submit buttons when the number of buttons is variable?

What i have tried to accomplish here is to fetch data from database and display it a form.
How to name the submit buttons so that i can identify them on the actions page?
if(isset($_POST["sch"]))
{
$_SESSION['e']=$_POST["phon"];
$result_set=mysql_query("select * from bill_info where phone='".$_SESSION['e']."' and net_payable=0 order by bill_no");
if($row=mysql_fetch_array($result_set))
{
echo "<form name=\"shpen\" method=\"post\" action=\"vgbill2.php\"> <table border=\"0\">";
do
{
echo "<tr><th>Bills</th><th>Action</th></tr>";
echo "<tr><td>".$row[0]."</td><td><input type=\"submit\" name=\"".$row[0]."\" value=\"Generate\"></td></tr>";
} while($row=mysql_fetch_array($result_set));
//echo mysql_errno($con) . ": " . mysql_error($con) . "\r\n";
echo "</table></form>";
}
else echo "\r\n"." No bills pending for given phone number"." \r\n";
}
Use a button instead of an input:
echo '<button type="submit" name="bt_submit" value="'.$row[0].'">Generate</button>';
So you get the former name in $_POST['bt_submit'].
Since you are creating dynamic form and submitting the data, you don;t have to follow any special naming convention. Please use submit button name as "Save" and set one hidden filed as BillId and in your action page, check if isset($_POST['Save']) { // Do actions based on $_POST['BillId']}.

Mark buttons with unique ID and identify this ID value upon button clicked

We have html site based on php+mysql. On a page, there is table (4 rows and 1 column) having information about users. Each table cell has user name and appropriate button under it. User names populated to table using SELECT statement.
$q = "select usr.user_id, usr.nickname from users usr";
$r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));
Then info get's populated into table
echo "<table border cellpadding=1>";
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)){
echo "<tr>";
echo "<td>" . $row['nickname'] . "</td> <form name ='form_type' method ='GET'><input type = 'button' name = " . $row['user_id'] . " value = 'ButtonValue' id = 'ButtonId' onclick='processFormData();'></form></td>";
}
echo "</table>";
Javascript for getting ButtonName
<script type="text/javascript">
function processFormData() {
var name_element = document.getElementById('ButtonId');
alert(name_element.name);
}
Alert is using for testing.
My aim is to get user_id value upon button clicked. Currently I'm getting same user_id (firstly found) for all buttons.
Try this:
echo "<td>" . $row['nickname'] . "</td> <form name ='form_type' method ='GET'><input type = 'button' name = " . $row['user_id'] . " value = 'ButtonValue' id = 'ButtonId' onclick='processFormData(this);'></form></td>";
And this:
function processFormData(name_element) {
alert(name_element.name);
}
You have to pass User ID to JavaScript function like this,
<input type = 'button' name = " . $row['user_id'] . " value = 'ButtonValue' id = 'ButtonId' onclick='processFormData('<?php echo $row['user_id']; ?>');'>
In Script, you have to change the function link this,
<script type="text/javascript">
function processFormData(uid) {
alert(uid);
}
</script>
The id of ButtonID is on every button. This means none of them are unique. So, your script starts looking, and gives the same one every time.
You could just switch the name and id attributes (you'll need some text so the ID isn't just a number, that's not allowed):
<input type='button' id='btn".$row['user_id']."' value='ButtonValue' name='ButtonId' onclick='processFormData();'>
and then alert the (new, unique) ID:
alert(name_element.id);
But now since your ID has changed, your Javascript code won't find ButtonId anymore. So, you'll need to pass the button object to the Javascript directly. It could look like this:
HTML
<input type='button' id='btn".$row['user_id']."' value='ButtonValue' onclick='processFormData(this);'>
JS
function processFormData(element) {
alert(element.id);
}

accept/decline submit buttons looping with php

I'm trying to allow a user to accept/decline requests for an event through submit buttons. Information is looped and displayed in a row (username, location, accept,decline).
Right now 2 users are being displayed; User 1 and User 2(current ones for testing). Anyway, I'm trying to get the correct userid to work with the correct username. Currently, regardless of which user I accept or decline, user 2 is displayed. I tried to set the value of the userid based on a hidden input but it's not working correctly.
Here is my code.
for($i=0;$i<count($userExplode)-1;$i++){
$user = mysql_query("select userid,username from users where userid = ".$userExplode[$i]." ");
$user = mysql_fetch_array($user);
$userLoc = mysql_query("select userLocation from userinfo where userid = ".$userExplode[$i]." ");
$location = mysql_fetch_array($userLoc);
$locationExplode = explode("~",$location['userLocation']);
//the displayed output is working correctly so I know it's setting $user['userid'] properly
echo '<form method="post"><table><tr><td>' . $user['username'] . '</td>
<td>' . $locationExplode[0] . ', ' . $locationExplode[1] . '</td>
<td><input type="hidden" name="userReq" value='.$user['userid'].'></td>
<td><input type="submit" name="accept" value="Accept Request" ></td>
<td><input type="submit" name="decline" value="Decline Request" ></td></tr>';
}
echo '</table></form>';
}
if(isset($_POST['accept'])){
echo $_POST['userReq']; //displays user 2 even if I click user 1
}
if(isset($_POST['decline'])){
echo $_POST['userReq']; //also displays user 2 even if i click user 1
}
}
There is a lot wrong with your code:
You don't close the for's in the loop
there is no action on your form
you're starting a new table for each loop
Replace the submit button's by anchors and add the parameters in there. Then you can style the anchor to look like a button.
<input type="submit" name="decline" value="Decline Request" >
becomes
echo "Decline request";
Remove all the <form>s and load everything in 1 table.
Result:
<?php
if(isset($_GET['action']) AND isset($_GET['userid'])){
switch($_GET['action']){
case "accept":
// do whatever
break;
case "decline":
// do whatever
break;
default:
die('something wrong');
break;
}
}
echo '<table width="100%">';
for($i=0; $i <= count($userExplode); $i++){
$q = "
SELECT u.userid,u.username, userLocation
FROM users u
INNER JOIN userLocation ul ON u.userid = ul.userid
WHERE u.userid = ".$userExplode[$i]."
";
$rs = mysql_query($q) or die(mysql_error());
$user = mysql_fetch_array($rs);
$locationExplode = explode("~",$user['userLocation']);
//the displayed output is working correctly so I know it's setting $user['userid'] properly
echo '<tr><td>' . $user['username'] . '</td>'.
'<td>' . $locationExplode[0] . ', ' . $locationExplode[1] . '</td>'.
'<td>Accept Request</td>'.
'<td>Decline Request</td></tr>';
}
echo '</table>';
I think this is only the tip of the iceberg.. How do you get $userExplode for example? It is very weird and illogical. I assume that you first run a query to get all the users and then loop with this for?
In your example it looks like you have some code issues. Here it is cleaned up a little:
for($i=0;$i<count($userExplode)-1;$i++) {
$user = mysql_query("select userid,username from users where userid = ".$userExplode[$i]." LIMIT 1");
$user = mysql_fetch_array($user);
$userLoc = mysql_query("select userLocation from userinfo where userid = ".$userExplode[$i]." LIMIT 1");
$location = mysql_fetch_array($userLoc);
$locationExplode = explode("~",$location['userLocation']);
echo '<form method="post" action=""><table><tr><td>' . $user['username'] . '</td>
<td>' . $locationExplode[0] . ', ' . $locationExplode[1] . '</td>
<td><input type="hidden" name="userReq" value='.$user['userid'].'></td>
<td><input type="submit" name="accept" value="Accept Request" ></td>
<td><input type="submit" name="decline" value="Decline Request" ></td></tr>';
echo '</table></form>';
}
if(isset($_POST['accept'])){
echo $_POST['userReq']; //displays user 2 even if I click user 1
}
if(isset($_POST['decline'])){
echo $_POST['userReq']; //also displays user 2 even if i click user 1
}
Based on your code, the array that's being passed should be:
$users = "1|2";
$userExplode=explode("|",$users) // or whatever your delimiter is
To test, do a var_dump($userExplode); prior to starting your loop to make sure you've exploded the entries going it.
A source dump of the original page would be helpful as well. If you could post that then I could see how your code is rendering the html form.

Dynamicly creating and checking checkboxes in php

I am trying to dynamically create php check-boxes linked to an MSSQL-Database. The idea is to List every item in the table, with a check box. From there the user will be able to check the check-boxes and click submit to change the value in 1 field of the Database to "A". I have the database linked to the php and It outputs the check-checkboxes and table values, however I do not know from there how to dynamically check the check-boxes to see if they are checked, or to use it from there.
This is roughly the approach you want to take to dynamically create checkboxes. There are of course prettier ways to accomplish this (i.e. Smarty templates).
<html>
...
<form method="post" action="submit.php">
<?php
// connect to DB here
$result = mysql_query("SELECT l.id, l.name, u.checked FROM List l LEFT JOIN UserAnswers u ON l.id = u.list_id WHERE u.user_id = 5");
while ($row = mysql_fetch_assoc($result))
{
echo '<input type="checkbox" name="cb_' . $row['id'] . '" ' .
'id="cb_' . $row['id'] . '" ';
if($row['checked'])
echo 'checked';
echo " />\n"
echo '<label for="cb_' . $row['id'] . '">' . $row['name'] . "</label><br />\n";
}
?>
<input type="submit" value="Submit" />
</form>
...
</html>
submit.php is a bit trickier. When a checkbox is checked, it will set a post item. However if it's unchecked, you won't get ANYTHING back, so you need to check your database for all the items you'll be expecting.
<?php
// connect to DB here
$result = mysql_query("SELECT id, name, checked FROM things");
$answers = Array();
while ($row = mysql_fetch_assoc($result))
{
$checked = isset($_POST['cb_' + $row['id']]);
$answers[$row['id']] = $checked;
}
// update your database here using $answers
foreach ($answers as $id => $checked)
{
$query = "REPLACE INTO UserAnswers SET user_id=5, list_id=" . $id . ", checked=";
if($checked)
$query .= "1";
else
$query .= "0";
mysql_query($query);
}
This is all off the top of my head, there are better ways to do most of this. It's just a general direction. I make no guarantees about any of this. Oh and it looks quite vulnerable to SQL injection, watch out for that.

Categories