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?
2
Answers
Simply add PDO::FETCH_OBJ to the fetch PDO function
Like this:
Why? because the $userData is being setup to fetch an Object
This answer is assuming your method
->get()
returns astdClass
The problem can be the validation, if your function
->get()
is returning anstdClass
, yourif
will return true even if the object if empty. Here is an example using psysh:As you can see an empty array doesn’t pass the if condition, but the stdClass does.
To fix it you can parse your stdClass into an array:
You can also check for specific values if they exist.