Jump to content

Issue with form sending proper $_POST data


OGirly

Recommended Posts

I usually hate to post something like this as a first post...I'd like to at least do an into but I"m stumped and I think it's a totally stupid thing I"m not noticing. Anyway, this is the final step in a three step user verification; this is for a staff user to be verified. Anyway, by now they have already verified their email and entered a random code so I"m only worried about actually setting them to verified status in my database so they can start working on blogs etc.

 

Anyway, this form is supposed to find all unverified staff members, and allow an admin to easily just click down the list (one at a time currently) and verify the user (ie. setting their database status to verified_staffUser). The username that is supposed to be verified (or declined and therefore their entry deleted) is supposed to be passed through as  $_POST[vnsupUsername]. This is set each time it loops through and prints a new user.

 

The problem is that it's only sending the final username when I click verify/decline on any user :\. I"m not sure why it's doing this. In firebug on firefox it's showing that the user name is set for each one to be properly in the form...but when I click on it (I am having on my machine) the username being worked with echoed..and it's always the last one that was entered into the database. I have no idea why this is happening :(..any thoughts?

 

<?php 
if(isset($_GET[vnsufac]) || isset($_POST[svnsu]) || isset($_POST[dvnsu])){ 
	// simply prints the back home button
	echo "<form action=\"http://localhost/~atharp1122/OGirly_Site/ogirly_staff_homepage.php\" method=\"post\">"
			        ."<input type=\"submit\" value=\"Back to Staff Homepage\" style=\"margin-top:10px;\">";



	// this will print out the form to verify/deny all new staff user requests that have been email verified				
	$programCheckUVStaff = mysql_query("SELECT username, email, firstname, lastname FROM staffUNAP where verified_staff = '0'");
		while($UVStaff = mysql_fetch_assoc($programCheckUVStaff)){
	      print "<div class=\"newVerifyUserContain\" >";
		    print "<div class=\"newVerifyUser\" >";
			  echo "<h3 style=\"text-align: center;\">Would you like to verify this Staff request?</h3>";
			    echo "<table><tr><td>"
			      ."<img src=\"images/default_icons/di_bunny_rabbit.png\" width=\"56\" height=\"59\" />"
				  ."<ul style=\"padding-left: 100px; padding-bottom: 20px; margin-top: -42px; list-style-type: none;\"><li>"
				  ."{$UVStaff[username]} aka {$UVStaff[firstname]} {$UVStaff[lastname]}</li><li>"
				  ."{$UVStaff[email]}</li></ul></td></tr><tr><td>"
				    ."<form action=\"{$_SERVER[php_SELF]}\" method=\"post\">"
				      ."<input type=\"checkbox\" name=\"isadmin\" value=\"1\" style=\"margin-left: 10px;\">Is Admin?"
						."<input type=\"hidden\" name=\"vnsupUsername\" value=\"{$UVStaff['username']}\">"
					  ."<input type=\"submit\" name=\"svnsu\" value=\"Verify Staff\" style=\"margin-left: 200px;\">"
					  ."<input type=\"submit\" name=\"dvnsu\" value=\"Decline Request\">";
			    print "</table>";								
		  print "</div></div>";
		}
	}
	// verify a staff member
		if(isset($_POST[svnsu])){
			echo "verifying a new user";
			echo $_POST[vnsupUsername];
		}
?>

Link to comment
Share on other sites

The problem is that each set of inputs you display in your loop have the same name per-loop-iteration.  So, for each db row's worth of inputs you display, you get an input with a name isadmin, an input with a name vnsupUsername, etc.  Names, like IDs, are supposed to be unique identifiers.  PHP knows this, which is why it can only 'see' the most recent one.  Each loop essentially overwrites what PHP can get a hold of.

 

You'll need to either create a unique name for each input during each iteration of your loop, or you'll need to store the values in an array by setting their names to be isadmin[] and vnsupUsername[].

Link to comment
Share on other sites

well I thought this would be really easy..but I"m still stumped and it's honestly starting to be really frustrating. I can get the forms to print with the values displaying for each individual user. I can also get the usernames, emails, first/last names etc into an array. I"m trying to have this search my database for any unverified staff requests, then allow an admin to verify each user (and set if they are an admin) one user at a time; not submitting every user each time. Why is this so hard? I guess it doesn't make sense, the unique name fields. How do I know which field to search for?

 

if I set each fields name individually how do I search for an isset? ie please excuse punctuation not using a text editor for this:

 

if(isset($_GET[verifyStaff])){
$requestCounter = 1;
$checkForUnverifiedStaff = mysql_query("SELECT username, email, firstname, lastname FROM staffUNAP where verified_staff = '0'");
  while($unverifiedStaff = mysql_fetch_array($checkForUnverifiedStaff)){
    print "<div class=\"containVerify\">;
      print "<div class=\"staffVerify\">;
        echo "<h3>Would you like to verify this user?</h3>";
          echo "<form action=\"{$_SERVER[php_SELF]}\" method\"POST\">"
            ."<input type=\"checkbox\" name=\"isAdmin{$requestCounter}\" value = \"1\">Is Admin?"
            ."<input type=\"hidden\" name=\"username{$requestCounter}\" value = \"{$unverifiedStaff[0]}\">
            ."<input type=\"submit\" name=\"verifyNewStaffUser{$requestCounter}\" value =\"verify\">"
         . "</form>";
    print "</div></div>";
  }
}

if(isset($_POST[???  What do I search for here? I don't know which user they are trying to verify :X ???)){
  this is where I get stuck  I don't know how to retreive a post variable I don't know the name for in a case like this  I can't just do
isset($_POST[$requestCounter])
}

 

ack..I'm soooo frustrated...I hate to say this but this issue has brought me to tears I have no idea what I am not getting about this...I am feeling really confused :( and I"m about ready to give up...bah! Three days on this..I just don't know what to do...I thought I understood what you guys said but I guess not...do you guys understand what I'm trying to do? Am I being clear? Sometimes I"m not very good at that...please help me I"m pretty desperate to get this project finished :(

Link to comment
Share on other sites

Hopefully this gets you going in the right direction.  The code basically spits out a form for each user and has a hidden input with the username to either approve/decline depending on which button was pressed.

 

I hope it's easy enough to follow...

 

<?php
$fake_db_data = array();
$fake_db_data[] = array('username' => 'Superman', 'firstname' => 'Clark', 'lastname' => 'Kent', 'email' => 'superman@email.com');
$fake_db_data[] = array('username' => 'Spiderman', 'firstname' => 'Peter', 'lastname' => 'Parker', 'email' => 'spiderman@email.com');
$fake_db_data[] = array('username' => 'Batman', 'firstname' => 'Bruce', 'lastname' => 'Wayne', 'email' => 'batman@email.com');

// Process the form submission if appropriate
if (isset($_POST['approve']))
{
// Google "php ternary operator" if you don't understand the next line
$username = isset($_POST['username']) ? (string) $_POST['username'] : FALSE;

if ($username)
{
	echo "The username to be verified was: " . htmlentities($username) . "<br />";
}
}
if (isset($_POST['decline']))
{
// Similar to the approval process
die('Not implemented (try approve).');
}
?>

<?php foreach ($fake_db_data as $person): ?>

<form action="" method="post">
<input type="hidden" name="username" value="<?php echo htmlentities($person['username']); ?>" />
<p>
	<strong>Username: </strong><?php echo htmlentities($person['username']); ?>
	<br />
	<strong>Name: </strong><?php echo htmlentities($person['firstname']) . ' ' . htmlentities($person['lastname']); ?>
	<br />
	<input type="submit" name="approve" value="Approve" />
	<input type="submit" name="decline" value="Decline" />
</p>
</form>

<?php endforeach; ?>

Link to comment
Share on other sites

You know for some reason I've never even encountered the ternary operator before, but it seems extremely useful is cases like this, or setting variables to user input etc! I'll post the php.net link to it as well so others can read (pretty much at the bottom of the comparison operators page (again a mystery why I've never even at least read about this (even in the O'Reilly books I"ve had to read though). Hmm...I think this should solve the problem; I'm going to work on it now, so I'll let you know!

 

here's the php.net link if anyone would like to read about this:

(again at the bottom of the page

http://php.net/manual/en/language.operators.comparison.php

Link to comment
Share on other sites

You solved it!

 

Here's how I did it in the end; hopefully someone else can use this too...great help! Thanks again :D

 

<?php 
if(isset($_GET[vnsufac])){ 
	// simply prints the back home button
	echo "<form action=\"http://XXXXXXXXX.php\" method=\"post\">"
			        ."<input type=\"submit\" value=\"Back to Staff Homepage\" style=\"margin-top:10px;\">";

// perform database query, create arrays for each unverified staff request
	$UNVSRA = array();
	  XXXXX_db_connect();
	    $UNVSRA = mysql_query("SELECT username, 
									  email, 
									  firstname, 
									  lastname FROM staffUNAP WHERE verified_email = 1 AND 
																	verified_staff = 0");
		$request_counter = 1;				
		while($UNVSRA2[$request_counter] = mysql_fetch_assoc($UNVSRA)){
			  $data[$request_counter] = array('0' => $UNVSRA2[$request_counter][username],
											  '1' => $UNVSRA2[$request_counter][email],
											  '2' => $UNVSRA2[$request_counter][firstname],
    											  '3' => $UNVSRA2[$request_counter][lastname],
											  '4' => $request_counter);
			  
			// print the form per entry 
			print "<div class=\"newVerifyUserContain\" >";
			  print "<div class=\"newVerifyUser\">";
			    print "<form action=\"{$_SERVER[php_SELF]}\" method=\"post\">";
				  print "<ul><li>";
				    echo "USERNAME: {$data[$request_counter][0]}<li>"
					  ."<li><input type=\"hidden\" name=\"username\" value=\"{$data[$request_counter][0]}\"></li>"
					  ."<li><input type=\"submit\" name=\"approve\" value=\"approve\"></li>"
                          ."<li><input type=\"submit\" name=\"reject\" value=\"reject\"></li>";
				  print "</ul>";
				print "</form>";
			  print "</div>";
			print "</div>";
			$request_counter++;
	    }close_connection($XXXXXXXX_db_connection);
}
   if(isset($_POST[approve])){
  $username = isset($_POST['username']) ? (string) $_POST['username'] : FALSE;
	echo $username;
}
?>

Link to comment
Share on other sites

hmm...no it's still not inserting the last one to be approved. All of the other ones, I set it to about four test users etc, they all get approved; just not the last one. At first it appears to go away, but it's not set in the database. :\

Link to comment
Share on other sites

 if(isset($_POST[approve])){
  $usrname = isset($_POST['usrname']) ? (string) $_POST['usrname'] : FALSE;
	mysql_query("UPDATE staffUNAP SET verified_staff = 1 WHERE username = '$usrname'");
}

 

^ is what I am using to put it into the database; and yes username is spelled usrname in this case; it is intentional.

Link to comment
Share on other sites

I suggest splitting your code into two files.

 

File 1 will accept your GET parameter and display your form(s).  Form submission will send the POST data to File 2.

File 2 will validate the incoming data and update the db.  Upon completion, it will redirect the user to where ever you want them to go.

 

I think this split will help you see what's going on.  A non-updated entry means that the last username is not being set, given the WHERE clause in your query.  Splittinh the process up can help you isolate the problem.  You can always reintegrate them later.

Link to comment
Share on other sites

Thank you, I will try that when I get home today.

 

I'm sort of used to working with C++ so I thought PhP would be super easy, I feel like an ass now for thinking so. I seem to also be getting variables messed up etc. as I'm used to a really strict environment, this is quite a bit different. I'll try the two files and see if I can't figure out the problem by splitting it up as you recommended.

 

<?php include("".XXX); ?> to include the new file correct?

Link to comment
Share on other sites

Thank you, I will try that when I get home today.

 

I'm sort of used to working with C++ so I thought PhP would be super easy, I feel like an ass now for thinking so. I seem to also be getting variables messed up etc. as I'm used to a really strict environment, this is quite a bit different. I'll try the two files and see if I can't figure out the problem by splitting it up as you recommended.

 

<?php include("".XXX); ?> to include the new file correct?

 

You don't need to include a file in this case.  Simply point your form's action to the second file, then have the second file use a header redirect to where ever you want the user to go.

 

Why do it like this?  Because you'll be separating the code that displays the form(s) from the code that processes the form data, giving you a clear divide between the two.

 

So, the first file would do the work of obtaining the GET value, querying the db for all of the entries that need to be changed, and displaying them as forms.  The second file would simply take that data, validate it, insert it into the db, then send the user somewhere else.  No output from it, just pure PHP processing.

Link to comment
Share on other sites

I tried that and it's still not working; for some reason it will always insert the data except for the last one; even on a different file...grrrr...

 

I have something at the end that's telling me that there are no more users that are unverified after I go through and accept everyone, but when I go to look at the database(and upon reload of the page) the last one that I clicked approve on (regardless of order in the print out it could have been the first, second third etc) will not submit; but it's also not giving me any sql errors at all...what could be happening here??

This is the new file, the processing file:

<?php include("constants/ogirly_db_login_constants.php"); ?>
<?php
if(isset($_POST[approve])){
  if(isset($_POST['usrname'])){
	  $usrname= $_POST['usrname'];
  
  ogirly_db_connect();
  	$query = "UPDATE staffUNAP SET verified_staff = '1' WHERE username = '{$usrname}'";
	mysql_query($query);
	close_connection($ogirly_db_connection);
	if(mysql_error()){
		echo mysql_error();
	}
  	else{
  header("location: http://localhost/~atharp1122/OGirly_Site/ogirly_staff_homepage.php");
	}
   }
}
else{
	echo "No POST SENT";
}

?>

 

and here is the other file:

 

<?php 

if(isset($_GET[vnsufac])){ 
	// simply prints the back home button
	echo "<form action=\"http://localhost/~atharp1122/OGirly_Site/ogirly_staff_homepage.php\" method=\"post\">"
			        ."<input type=\"submit\" value=\"Back to Staff Homepage\" style=\"margin-top:10px;\"></form>";

// perform database query, create arrays for each unverified staff request
	$UNVSRA = array();
	  ogirly_db_connect();
	    $UNVSRA = mysql_query("SELECT username, 
									  email, 
									  firstname, 
									  lastname FROM staffUNAP WHERE verified_email = 1 AND 
																	verified_staff = 0");
		$request_counter = 0;				
		while($UNVSRA2[$request_counter] = mysql_fetch_assoc($UNVSRA)){
			  $data[$request_counter] = array('0' => $UNVSRA2[$request_counter][username],
											  '1' => $UNVSRA2[$request_counter][email],
											  '2' => $UNVSRA2[$request_counter][firstname],
    											  '3' => $UNVSRA2[$request_counter][lastname],
											  '4' => $request_counter);
			  
			// print the form per entry 
			print "<div class=\"newVerifyUserContain\" >";
			  print "<div class=\"newVerifyUser\">";
			    print "<form action=\"http://localhost/~atharp1122/OGirly_Site/process_staff.php\" method=\"post\">";
				  print "<ul><li>";
				    echo "USERNAME: {$data[$request_counter][0]}<li>"
					  ."<li><input type=\"hidden\" name=\"usrname\" value=\"{$data[$request_counter][0]}\"></li>"
					  ."<li><input type=\"submit\" name=\"approve\" value=\"approve\"></li>"
                          ."<li><input type=\"submit\" name=\"reject\" value=\"reject\"></li>";
				  print "</ul>";
				print "</form>";
			  print "</div>";
			print "</div>";
			$request_counter++;
	    }close_connection($ogirly_db_connection);
}

?>

 

here's the login program that is on the page the data is input into; it has a notification of new staff user requests that appears in the login div, and it keeps track of any unverified requests. It counts down, even disappearing after I click on the last user..but it's not actually updating to the database. This is really holding me back on finishing this last bit of this project..I really have no idea why it's not working :( I really appriciate your help on this, because I"m totally at a loss at what to do and it's been like three days (four really I tried for a day and a half before contacting the forums) and I still can't figure this out...omg soooo frustrating :( It seems like what I am trying to do should be SO simple :\

 

<?php 
//Staff Login

// Check for Logout
if(isset($_POST[logout])){
	unset($_SESSION[username], $_SESSION[login], $_SESSION[staffLogin], $_SESSION[admin]);
}
// Check for previous Login
if(isset($_SESSION[login]) && $_SESSION[staffLogin] == 1){
			if($_SESSION[admin] == 1){
				check_unverified_staff();
				}
				else{
					check_unverified_staff();
				}
		    
	echo "<form action =\"{$_SERVER[php_SELF]}\" method=\"post\" style=\"padding-top: 60px;\" >";
	echo "Logged in as {$_SESSION[username]}<br/>";
	echo "<input type=\"submit\" name=\"logout\" value=\"Logout\"></form>";
	}
// Check for new login
elseif(isset($_POST[username])){
	if((preg_match("/^\w{4}\w{1,11}\w$/", $_POST[password])) && 
	   (preg_match("/^\w{4}\w{1,13}\w$/", $_POST[username]))){
		ogirly_db_connect();
		$loginQuery = mysql_query("SELECT password, verified_staff, verified_admin FROM staffUNAP WHERE username = '$_POST[username]'");
		$loginArray = mysql_fetch_array($loginQuery);
		close_connection($ogirly_db_connection);
		if($loginArray[0] == $_POST[password] && $loginArray[1] == 1){
			$_SESSION[username] = $_POST[username];
			$_SESSION[login] = 1;
			$_SESSION[staffLogin] = 1;
			// check to see if admin : if admin, post admin notices
			if($loginArray[2] == 1){
				$_SESSION[admin] = 1;
				check_unverified_staff();
			} //end admin check
			echo "<form action =\"{$_SERVER[php_SELF]}\" method=\"post\" style=\"padding-top: 60px;\" >";
			echo "Logged in as {$_SESSION[username]}<br/>";
			echo "<input type=\"submit\" name=\"logout\" value=\"Logout\"></form>";
		}
		else {print_login_form();}
	}
	else {print_login_form();}
}

// First time visit/Default Action/Logout Action
else {print_login_form();}

Link to comment
Share on other sites

Well, for one, you're making your life much harder than it needs to be with your loop.  When you fetch things associatively, you don't need to manually set the returning array's keys.  PHP is nice with db handling in that it does the work for you.  Also, since all of your inputs except for your buttons are hidden, you don't need to put them in a list.  Your while-loop can be distilled to:

 

while($row = mysql_fetch_assoc($UNVSRA))
{
   // print the form per entry 
   echo '<div class="newVerifyUserContain" >';
   echo '<div class="newVerifyUser">';
   echo '<form action="http://localhost/~atharp1122/OGirly_Site/process_staff.php" method="post">';
   echo 'USERNAME: ' . $row['username'];
   echo '<input type="hidden" name="usrname" value="' . $row['username'] . '">';
   echo '<input type="submit" name="approve" value="approve">';
   echo '<input type="submit" name="reject" value="reject">';
   echo '</form></div></div>';
}

 

For more on this, look at: mysql_fetch_assoc.

 

Put your if (mysql_error()) conditional above the line where you close the connection in your form-handling file.  I have the feeling that any errors you may be getting are getting hidden by you closing the connection before handling them.  I also suggest commenting out your header redirection and trying to echo your username variable in your form-handling file as a debugging measure.  Something like:

 

echo "Is the username set: $usrname";

 

To see if the value is indeed getting set properly.

 

If all else fails, put the following two lines at the top of your files:

 

ini_set("display errors", 1);
error_reporting(-1);

 

This will force PHP to display all errors, if any errors are occurring.

Link to comment
Share on other sites

Okay, so here's what I have now, pretty much just the changes you recommended; it's making progress. If I redirect to somewhere like google lets say it works just fine, but if I redirect back to the page with a ?vnsufac sent to allow an admin to just accept or reject another user it does not update any of them :( temporiarily it will stop them from showing, but it will not update them in the database. It will appear that all three have been done, but again...none are. If i have it redirect to somewhere like google. The one that I did does get updated, and it finally will update the last one; but never if I redirect to the ogirly_staff_homepage.php or ogirly_staff_homepage.php?vnsufac=1. Something must be going screwy here...here's the code...again thanks for helping with this. At least it's inputting the data. It's pretty similar to before; just made the clean ups you recommended etc. Still not sure why it's not working when I redirect back to the site though... :\

 

(Processing form is the second bit of code posted)

 

<?php 
if(isset($_GET[vnsufac])){ 
	// simply prints the back home button
	echo "<form action=\"http://localhost/~atharp1122/OGirly_Site/ogirly_staff_homepage.php\" method=\"post\">"
			        ."<input type=\"submit\" value=\"Back to Staff Homepage\" style=\"margin-top:10px;\"></form>";

	// perform database query, create arrays for each unverified staff request
	$UNVSRA = array();
	  ogirly_db_connect();
	    $UNVSRA = mysql_query("SELECT username, 
									  email, 
									  firstname, 
									  lastname FROM staffUNAP WHERE verified_email = 1 AND 
																	verified_staff = 0");
	   // print the form per entry 				
	   while($row = mysql_fetch_assoc($UNVSRA)){
	   echo '<div class="newVerifyUserContain" >';
	   echo '<div class="newVerifyUser">';
	   echo '<form action="http://localhost/~atharp1122/OGirly_Site/process_staff.php" method="post">';
	   echo 'USERNAME: ' . $row['username'];
	   echo '<input type="hidden" name="usrname" value="' . $row['username'] . '">';
	   echo '<input type="submit" name="approve" value="approve">';
	   echo '<input type="submit" name="reject" value="reject">';
	   echo '</form></div></div>';
	   }close_connection($ogirly_db_connection);
}
?>

 

<?php
if(isset($_POST[approve])){
  if(isset($_POST['usrname'])){
	  $usrname = isset($_POST['usrname']) ? (string) $_POST['usrname'] : FALSE;
  	    ogirly_db_connect();
  		  $query = "UPDATE staffUNAP SET verified_staff = '1' WHERE username = '{$usrname}'";
		    mysql_query($query);
			  if(mysql_error()){
			    echo mysql_error();
				  close_connection($ogirly_db_connection);
			  }
			  else{
				close_connection($ogirly_db_connection);
				//echo "usrname = " .$usrname;
  			    header("location: http://localhost/~atharp1122/OGirly_Site/ogirly_staff_homepage.php?vnsufac");
			  }
   }
   else{ echo "usrname not set";}
}
else{ echo "no post data sent";}
?>

Link to comment
Share on other sites

we'll it's working now; so I"m going to assume that the last post has some typeo that I've since caught. Thank you for all your help; you have no idea how helpful you've been! Looking forward to learning this language a bit more seems pretty great!

 

~alice

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.