I am trying to put myself in OOP and I have a problem with variable scope.
Everything works except a session array and everything posts correctly.
My 'session table' and its elements are declared but its variables remain undefined. I get the following error messages:
Notice: Undefined variable: row
Notice: Trying to get property of non-object
What I can do to get access to $row
?
This is my code for the class, including its methods:
$db = db::connect();
class auth {
protected $login;
protected $password;
protected $email;
public function setLogin($login) {
$this->login = $login;
}
public function setPassword($password) {
$this->password = $password;
}
public function login($fields, $table, $col_login, $col_password) {
$query = Db::getInstance()->prepare('SELECT ' . $fields . ' FROM ' . $table . ' WHERE ' . $col_login . ' = :login AND ' . $col_password . ' = :password');
$query->bindValue( ':login', $this->login, PDO::PARAM_STR);
$query->bindValue(':password', $this->password, PDO::PARAM_STR);
$query->execute();
if ($query->rowCount() > 0) {
$row = $query->fetch(PDO::FETCH_OBJ);
echo '<pre>';
print_r($row->u_login);
echo '</pre>';
return true;
}
else {
return false;
}
$query->closeCursor();
}
}
Here is my form code; this is from where I call the class method:
<?php
session_start();
if (isset($_POST['login_submit'])) {
if (!empty($_POST['login']) && !empty($_POST['password'])) {
$auth = new auth();
$auth->setLogin($_POST['login']);
$auth->setPassword(sha1($_POST['password']));
if ($auth->login('u_login,u_password,u_email,u_id_level', 'users', 'u_login', 'u_password')) {
$_SESSION['back_office'] = array(
'login' => $row->u_login, // Error, $row is undefined
'level' => $row->u_level,
'email' => $row->u_email
);
}
else {
message::showError('Compte non reconnu');
}
}
else {
message::showError('Veuillez remplir tous les champs');
}
}
?>
<form action="test.php" name="loginform" method="post">
<input type="text" name="login" />
<input type="password" name="password" />
<input type="submit" name="login_submit" value="Se connecter" />
</form>