qadenza
qadenza

Reputation: 9293

splitting a function inside a class

This is a function inside a class and it works

public function login($username,$password){

        $hashed = $this->get_user_hash($username);

        try {
            $stmt = $this->_db->prepare('SELECT username FROM members WHERE password = :password AND active="Yes" ');
            $stmt->execute(array('password' => $hashed));
            $row = $stmt->fetch();
            $_SESSION["uname"] = $row['username'];
        }
        catch(PDOException $e) {
            echo '<p class="bg-danger">'.$e->getMessage().'</p>';
        }

        if($this->password_verify($password,$hashed) == 1){
            $_SESSION['loggedin'] = true;
            return true;
        }   
    }

Now, I want to separate the above code into two functions

public function login($username,$password){

    $hashed = $this->get_user_hash($username);

    if($this->password_verify($password,$hashed) == 1){
        $_SESSION['loggedin'] = true;  // this works
        return true;
    }   
}

The above code also works, but in the bellow part I cannot get the value of $_SESSION["uname"]

public function get_uname(){

        $hashed = $this->get_user_hash($username);

        try {
            $stmt = $this->_db->prepare('SELECT username FROM members WHERE password = :password AND active="Yes" ');
            $stmt->execute(array('password' => $hashed));
            $row = $stmt->fetch();
            $_SESSION["uname"] = $row['username'];  // this doesn't work
        }
        catch(PDOException $e) {
            echo '<p class="bg-danger">'.$e->getMessage().'</p>';
        }

    }

Upvotes: 0

Views: 64

Answers (1)

serakfalcon
serakfalcon

Reputation: 3531

It's actually simple when you take a step back and look at it.

your first function is like this:

public function login($username,$password){

note, you pass $username, which gets picked up by:

 $hashed = $this->get_user_hash($username);

in your new split function, you don't pass $username

public function get_uname(){

    $hashed = $this->get_user_hash($username); //where is username coming from?

so, presumably $this->get_user_hash() will return whatever you've programmed it to when the input is null (maybe false), and so your query is not working because $hashed isn't anything meaningful. Make sense?

Upvotes: 2

Related Questions