I was creating a user management system, then I stored four user sessions in an array after user has logged in. Like the following:
$se = new UserModel($this->pdo);
$userData = $se->get($email);
if ($userData) {
$userDataArray = [
'email' => $email,
'first_name' => $userData->first_name,
'last_name' => $userData->last_name,
'roles' => $userData->roles
];
var_dump($userData);
$_SESSION['USER_DATA'] = $userDataArray;
}
but it was empty when I tried to use the first name and last_name like:
<?=$_SESSION['USER_DATA']['first_name'] ." ". $_SESSION['USER_DATA']['last_name']?>
and I print_r the $_SESSION variable which gives and showing the other array of session is empty:
array(1) {
["USER_DATA"]=> array(4) {
["email"]=> string(15) "[email protected]"
["first_name"]=> NULL
["last_name"]=> NULL
["roles"]=> NULL
}
}
How do I solve this please?
Simply add PDO::FETCH_OBJ to the fetch PDO function
Like this:
public function get($email) {
$sql = "SELECT * FROM $this->table WHERE email = :email";
$stmt = $this->pdo->prepare($sql);
$stmt->bindParam(':email', $email);
$stmt->execute();
$user = $stmt->fetch(PDO::FETCH_OBJ);
return $user;
}
Why? because the $userData is being setup to fetch an Object