skip to Main Content

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


  1. Chosen as BEST ANSWER

    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


  2. This answer is assuming your method ->get() returns a stdClass

    The problem can be the validation, if your function ->get() is returning an stdClass, your if will return true even if the object if empty. Here is an example using psysh:

    > $a = new stdClass
    = {#2760}
    
    > if ($a) { echo "here";}
    here⏎
    > $a
    = {#2760}
    
    > $a = []
    = []
    
    > if ($a) { echo "here";}
    

    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:

    if ((array)$a) { echo "here";}
    

    You can also check for specific values if they exist.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search