0

I am having trouble calling the variable inside my class method. Variable userId won't display on screen. Below is my class and my index.php file. I want to display the userId of the user after form submission.

class validateLogin 
{
    public $id;
    public $username;
    public $password;

    public function __construct($aUserName,$aUserPassword) 
    {       
        $this->username = $aUserName;
        $this->password = $aUserPassword;
    }

    public function checkUser() 
    {
        $conn = new dbconnection();
        $dbh = $conn->connect();

        $query = $dbh->prepare("SELECT id FROM tbluser WHERE username=:username AND password=:password");
        $query->bindParam(":username", $this->username);
        $query->bindParam(":password", $this->password);

        $query->execute();  

        $counts = $query->rowCount();       

        if($counts==1) {        
            $results = $query->fetch();
            $this->id = $results['id'];
        }
    }
    public function getUserId() {
        return $this->id;
    }       

}

My index.php is below (assume that the submit button has been clicked)

require_once 'classes/class.Database.php';
require_once 'classes/class.Validation.php';

if(isset($_POST['submit'])) {
    if(!empty($_POST['username']) && !empty($_POST['password'])) {              
        $user = new validateLogin($_POST['username'],$_POST['password']);           
        echo getUserId()
    }
}

2 Answers 2

5

The constructor is not calling the:

checkUser();

You need to make the constructor do that or:

require_once 'classes/class.Database.php';
require_once 'classes/class.Validation.php';

if(isset($_POST['submit'])) {
    if(!empty($_POST['username']) && !empty($_POST['password'])) {              
        $user = new validateLogin($_POST['username'],$_POST['password']);
        $user->checkUser();
        echo $user->getUserId();
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

You need to reference the object

echo getUserId()

should be

echo $user->getUserId()

1 Comment

then id isn't getting set, the function is getting called fine. and the other answer tells you how to get the id set.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.