我的php脚本有问题。我需要它来获取有关用户的所有信息。我真的不知道问题是什么,但是如果我echo $userInfo->username;
它没有显示任何东西。我得到了与数据库的连接。
函数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>';
}
}
答案 0 :(得分:2)
您的函数返回一个关联数组,但是从您的描述中,您将像对象一样访问返回值。
如果要像对象一样访问返回值,请编写如下函数:
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
如果要像数组一样访问返回值,请编写如下函数:
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