views:

184

answers:

3

UPDATE: I solved the problem myself and the answer is below. Carry on...

I have a form for updating your account using PHP and mySQL. On submit, it assigns all of the $_POST variables to the new user() object, and then does an update() method on the user object which runs an UPDATE query in SQL.

The form obviously defaults to all of the user's information, EXCEPT for the password, which I don't prefill. It's blank unless they want to change their password.

If I didn't do anything to address this, every account update would reset the person's password to "", since the field is blank on submit. That would be bad. So to fix it, I added this code:

    if(empty($_POST['password']) || is_null($_POST['password']) || !isset($_POST['password']) || $_POST['password'] == "") {
  $user->hashed_password = $edituser->hashed_password;
 } else {
  $password = $database->escape_value($_POST['password']);
  $user->hashed_password = md5($password);
 }

Basically, if the $_POST password value is blank, set the password to the current user's password ($edituser is an object created in advance to save the current user's info if needed). Believe me, I tried it first with just if(empty()) because empty should work, but it didn't, so I added the null, the isset, and even the !== "" just to be safe.

No matter what I do, the password is reset to blank. Why?

+1  A: 

Do you have warnings turn on? You might need to !isset($_POST['password']) first in your if statement

This has served me well with debugging stuff like this:

error_reporting(E_ALL | E_STRICT);
ini_set('display_errors','On');
Tim Santeford
A: 

Great, it turns out I'm just an idiot!

My User class has an attributes function that requires db field names to be identical to the object attribute names for it to work. My class attribute was $password, my db field name was "hashed_password" -- so it updated to blank no matter what.

That was a fun couple of hours!

Jason Rhodes
please edit that into your question!
tharkun
+1  A: 

Guys...

Even if the field is blank, it will still be present in $_POST.

$Password = trim(isset($_POST['Password']) ? $_POST['Password'] : '');

if($Password)
{
    //validate password
    //update password
}
gahooa