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.
Related
First time posting, and PHP is not my strongest area, so here goes...
My code below generates a list of buttons depending on how many values are found in my DB Table, then the second piece of code is supposed to trigger when the buttons are clicked. Everything is working except that the second piece of code only works for the last button generated. Any ideas?
<?php
$username = $_SESSION['sess_user'];
$con=mysql_connect('localhost','root','root') or die(mysql_error());
mysql_select_db('user_registration') or die("cannot select DB");
$loop = mysql_query("SELECT * FROM `vaults` WHERE username = '$username' ORDER BY vaultname asc") or die ('Error Getting User Data! <br />' .mysql_error());
$chk = mysql_num_rows($loop);
$myvalue = '';
while ($row = mysql_fetch_assoc($loop)) {
$myvalue = "{$row['vaultname']}";
echo '<form method="post"><input class="text-center" type="submit" name=' . $myvalue . ' value=' . $myvalue . ' id="vaultSelecter"></form>';
}
?>
<?php
if(isset($_POST[$myvalue])){
echo '<script type="text/javascript">window.onload = function() { document.getElementById("instructions").innerHTML = " HELLO WORLD! "; }</script>';}
?>
Thank you all for your replies, I appreciate it. I understand what everyone is saying, but the ID I reference in my getELementByID() is a separate DIV from the buttons, I want to change the content of the single DIV with the ID "instructions", when any of the buttons are clicked, but it only works for the last button created by the loop. Is that still due to the way I have my buttons ID'd?
For example say the above loop creates three buttons, I want each button to change the contents of the following DIV with "Hello Word".
<div id=instructions>
replace this text
</div>
I am guessing I have to store each of the $myvalues created by the loop into an array, so that each value can be assigned separately to each button, I just have no idea how to do that.
You're duplicating IDs in this line:
echo '<form method="post"><input class="text-center" type="submit" name=' . $myvalue . ' value=' . $myvalue . ' id="vaultSelecter"></form>';
and IDs must be unique. Try classes instead. Ex:
var elems = document.getElementsByClassName("text-center");
for (var i = 0; i < elems.length; i++) {
console.log('x')
elems[i].addEventListener('click', function () {
alert('hello');
}, false);
}
You're assigning multiple inputs to the same id, assign them to a class instead since id's have to be unique.
You're also making a form for every button, which seems kind of pointless to me, try this instead:
echo '<form method="post">';
while ($row = mysql_fetch_assoc($loop)) {
$myvalue = "{$row['vaultname']}";
echo '<input class="text-center vaultSelecter" type="submit" name=' . $myvalue . ' value=' . $myvalue . '>';
}
echo '</form>';
The id called vaultSelector is now a class, so can be accessed via getElementByClassName()
Instead of this:
name=' . $myvalue . ' value=' . $myvalue . ' id="vaultSelecter"
Maybe try
name="' . $myvalue . '" value=' . $myvalue . ' id="' . $myvalue . '"
In my opinion it is best to uniquely identify any elements that will be used as a programming element.
Just another piece of unsoliciated opinion. If you can put everything in one form it may make things easier. So when the button submits set a hidden field and continue with the form submit.
I've updated the code but keep getting new errors.
I'm really hoping that someone can help me and look at my code to see what is wrong.
I have a database table on a webpage and I have one edit button and one delete button on each table row. At the moment I'm just trying to get the delete button to work and it will just not delete the row in the database even though I selected that ID. It looks like it's picking up the correct ID.
Can someone tell what is wrong? Below is the code...
<?php
require 'connect.inc.php';
if (isset($_POST['delete']) && isset($_POST['id'])) {
$id = get_post('id');
$query = "DELETE FROM movies WHERE id='.$id.' LIMIT 1";
if (!mysql_query($query, $db_server))
echo "DELETE failed: $query<br>".
mysql_error() . "<br><br>";
}
$query = "SELECT * FROM movies, categories WHERE movies.genre_id = categories.genre_id";
$result = mysql_query($query);
if (!$result) die ("Database access failed:" .mysql_error()) ;
$rows = mysql_num_rows($result);
echo '<table><tr><th>Title</th><th>Release year</th><th>Genre</th><th>Director</th><th>Update</th><th>Delete</th></tr>';
for ($j = 0 ; $j < $rows ; ++$j) {
$row = mysql_fetch_row($result);
//$id = $row[0];
echo '<tr><td>' .$row[1] . '</td>' ;
echo '<td>' .$row[2] . '</td>' ;
echo '<td>' .$row[3] . '</td>' ;
echo '<td>' .$row[4] . '</td>' ;
echo '<td>'."<a href='edit_movie.php?edit=" . $row[0] . "'>Edit</a>".'</td>';
echo '<td><form action="index.php" method="POST">
<input type="hidden" name="delete" value="yes" />
<input type="hidden" name="id" value="'. $row[0] .'" />
<input type="submit" value="Delete" /></form>
</td></tr>' ;
}
echo '</table>';
include 'add_movie.php';
?>
You forget to close action attribute.
You have echo '<td><form action="index.php method="POST"> change it to
echo '<td><form action="index.php" method="POST">
Just to be clear: 'mysql_query' and accompanying commands is deprecated and should really not be used. The OP however stated that it was required for an assignment. The easiest way to replace them is to use 'mysqli_*' instead. For an example using parameter binding to avoid sql-injection:
http://www.php.net/manual/en/mysqli-stmt.bind-param.php
Shouldn't it be:
if (isset($_POST['delete']) && isset($_POST['id'])) {
$id = mysql_real_escape_string($_POST['id']);
...
See this link for some info on 'get_post':
PHP: Having a problem with get_post
The problem there was that the function 'get_post' was defined on the next page of the course literature, wich the asker hadn't noticed.
The variable $_POST['id'] contains the id-value sent from a form via an HTTP POST-request. You check if that value is set, and then you should assign it to '$id' like i wrote.
Your delete sql has wrong quotes
$query = "DELETE FROM movies WHERE id='.$id.' LIMIT 1";
change to either
$query = "DELETE FROM movies WHERE id=".$id." LIMIT 1";
or
$query = "DELETE FROM movies WHERE id=$id LIMIT 1";
Try changing the form action
'<td><form action="index.php" method="POST">
Also check your database connection is properly established
Perhaps this might help for get_post
PHP: Having a problem with get_post
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
}
}
}
I have a checklist that's broken down into days, stage, timeShow, and bandName. I am displaying the options from a database with this script and I'm trying to display the results (and eventually email them) to the user on the 'process' page. How do I carry over the $result_x to the following page?
Here's an example of one of the 'blocks' for Saturday, Stage 1 and the value of the selection is the 'ID' of the row.
UPDATE- Part one is solved. Now looking to get the results sent to an email address input by the user.
FORM SOLUTION- 'Selection.php'
$sql_Sat1 = "SELECT * FROM bandSched WHERE day='saturday' AND stage='stage 1'";
mysql_query($sql_Sat1);
$result_Sat1 = mysql_query($sql_Sat1);
while($row = mysql_fetch_array($result_Sat1))
{
echo "<ul><li>";
echo'<input type="checkbox" name="id[]" value="'.$row['id'].' " id="bandSched_' . $row['id'] . '" />';
echo '<label for="bandSched_' . $row['id'] . '">' . $row['timeShow']." ".$row['bandName'] . '</label>';
echo "</li></ul>";
}
SOLUTION- 'process.php'
if ( ! empty($_POST['id']))
{ foreach($_POST['id'] as $key => $id) { $_POST['id'][$key] = mysql_real_escape_string($_POST['id'][$key]); }
$in = implode(', ', $_POST['id']);
$sql_Sat2 = "SELECT * FROM bandSched WHERE id IN ($in) ORDER BY FIELD(id, $in)";
$result = mysql_query($sql_Sat2) or die('MySQL Error ' . mysql_errno() . ': ' . mysql_error());
}
if ( ! isset($result))
{
echo 'You did not select anything';
}
else
{
while ($row=mysql_fetch_assoc($result))
{
echo "<tr>";
echo "<td>". $row['timeShow'] ."</td><td>" . $row['bandName'] . "</td>";
echo "</tr>";
}
}
Unless you have the attribute checked="checked" in your <input type="checkbox" />, the value will not be sent with the form data.
Try this:
echo '<input type="checkbox" value="' . $row['id'] .'"name="selected" checked="checked" />';
Does this solve the problem?
Carrying data from page to page can either be done with Sessions, Cookies, or posting hidden form elements containing the data.
Sessions provide you the data, but you still need to make a valid query. The only thing that sessions do are store data on the server. They do not keep any of the program execution, variables, etc.
Your error message is telling you that mysql_fetch_array was not supplied a MYSQL result resource (and it wasn't you supplied it an integer of the id value). The query will not be remembered across the session.
Also, mysql_* is deprecated, use PDO or mysqli.
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.