Michael Westergaard Michael Westergaard - 5 months ago 14
PHP Question

Php function userInfo doesn't work

I have a problem with my php script. I need it to get all the information about the user. I don't really see what the problem is, but if I do

echo $userInfo->username;
it doesn't show anything. I got a connection to the database.

The function userInfo():

function userInfo(){

try {
$stmt = $this->_db->prepare('SELECT * FROM members WHERE username = :username');
$stmt->execute(array('username' => $_SESSION['username']));

$row = $stmt->fetch(PDO::FETCH_OBJ);

$username = $row->username;
$firstname = $row->firstname;
$lastname = $row->lastname;
$worktitle = $row->worktitle;
$email = $row->email;
$admin = $row->admin;
$address = $row->address;
$city = $row->city;
$zipcode = $row->zipcode;
$phone = $row->phone;

return array(
'username' => $username,
'firstname' => $firstname,
'lastname' => $lastname,
'worktile' => $worktitle,
'email' => $email,
'admin' => $admin,
'address' => $address,
'city' => $city,
'zipcode' => $zipcode,
'phone' => $phone
);

} catch(PDOException $e) {
echo '<p class="warning">'.$e->getMessage().'</p>';
}
}

Answer

Your function returns an associative array, but from your description, you are accessing the return value like an object.

If you want to access the return value like an object, write the function like this:

function userInfo() {
    try {
        $stmt = $this->_db->prepare('SELECT * FROM members WHERE username = :username');
        $stmt->execute(array('username' => $_SESSION['username']));
        $row = $stmt->fetch(PDO::FETCH_OBJ);  // fetch as object
        return $row;
    } catch(PDOException $e) {
        echo '<p class="warning">'.$e->getMessage().'</p>';
    }
} 

$userInfo = userInfo();
echo $userInfo->username;  // object syntax

If you want to access the return value like an array, write the function like this:

function userInfo() {    
    try {
        $stmt = $this->_db->prepare('SELECT * FROM members WHERE username = :username');
        $stmt->execute(array('username' => $_SESSION['username']));
        $row = $stmt->fetch(PDO::FETCH_ASSOC);  // fetch as array
        return $row;    
    } catch(PDOException $e) {
        echo '<p class="warning">'.$e->getMessage().'</p>';
    }
} 

$userInfo = userInfo();
echo $userInfo["username"];  // associative array syntax