Alam
Alam

Reputation: 53

Can't echo out user data on home page

This is the code for my function

 public function getuserData() {
  session_start();
  $username = $_SESSION['user']; 
  $getData = $this->db->prepare("SELECT * FROM users WHERE username=?");
  $getData->bindParam(1, $username);
  $getData->execute();
  $row= $getData->fetch(PDO::FETCH_ASSOC);
  $email = $row['email'];
  $user = $row['username'];
  echo $email. '<br />';
  echo $user;
}

<?php

require_once "class/user.php";

echo $user;
echo $email;


$object = new User();
$object->getUserData();

?>

and here is my home.php, the username, and email echo out but only from the function, if i try to do echo $email; on the home.php it doesn't print. I need to print it out on the home page so I can style the output.

Already tried starting session on home.php and it still doesn't work, as I already started it in the getUserData() function.

Upvotes: 0

Views: 63

Answers (1)

Josh Foskett
Josh Foskett

Reputation: 4121

Those variables are only in the scope of the function itself, if you want to access that information, you'd have to return the values from the function.

user.php

public function getUserData() {
  session_start();
  $username = $_SESSION['user']; 
  $getData = $this->db->prepare("SELECT * FROM users WHERE username=?");
  $getData->bindParam(1, $username);
  $getData->execute();
  $row= $getData->fetch(PDO::FETCH_ASSOC);

  return $row;
}

home.php

<?php

require_once "class/user.php";

$object = new User();
$userInfo = $object->getUserData();

echo $userInfo['username'] . '<br>';
echo $userInfo['email];

Upvotes: 1

Related Questions