When I use this code everything works fine, I can login

function pass($user,$pass){
        return password_hash("$user-$pass", PASSWORD_BCRYPT, ['cost' => 12]);
 }

However if I try to update with this code, it fails for some reason, any ideas?

function updatePassword(){
        $res = true;
        $stmt = $this->db->prepare("UPDATE users
            SET encodedpassword= ?
            WHERE username = ?");
        try{
			$password = password_hash($_POST['newPassword'], PASSWORD_BCRYPT, ['cost' => 12]);
             $stmt->execute([$password, $_SESSION['username']]);
        } catch (Exception $e) {
            $res = $e->getMessage();
        }
        return $res;
    }
    

    $_POST['newPassword'] doesn't contain the same thing as "$user-$pass" perhaps? Depends on what "fails for some reason" looks like; if later lookups expect the latter and don't find it because the former is there instead, that would count as a "fail".

      FWIW, that second function will return a "truthy" value even if the execute() throws an exception. Maybe it would better to do something like:

      class Whatever
      {
        public $error;
      
        function updatePassword()
        {
          $res = true;
          $stmt = $this->db->prepare("UPDATE users
                    SET encodedpassword= ?
                    WHERE username = ?");
          try {
            $password = password_hash($_POST['newPassword'], PASSWORD_BCRYPT, ['cost' => 12]);
            $stmt->execute([$password, $_SESSION['username']]);
            if($stmt->rowCount == 0)
            {
              $res = false;
              $this->error = "No matching row found to update."; // or whatever makes sense
            }
          } catch (Exception $e) {
            $res = false;
            $this->error = $e->getMessage();
          }
          return $res;
        }
      }
      

      If we're on FWIW topics, I'd be reluctant to embed $_SESSION and $_POST thus tying the update password function to a particular source of username and password information.

      cluelessPHP
      As it stands, updatePassword() doesn't take any arguments, hence its need to go fishing for values itself. You could write it as updatePassword($username, $password) and pass those values when you call the function.

      Write a Reply...