PHP PDO获取数据库指定行问题:无法显示用户company字段
Let's break down why your $_SESSION['company'] isn't displaying and fix it step by step:
1. The Root Cause
Looking at your code, two key pieces are missing:
- Your
get_user_hashfunction only selectspassword,username, andmemberIDfrom the database — it doesn't fetch thecompanyfield at all. - Even if it did pull the
companydata, yourloginfunction doesn't store that value in the user's session.
2. Step 1: Update the Database Query
First, modify the get_user_hash method in user.php to include the company column in your SELECT statement:
private function get_user_hash($username){ try { // Add `company` to the list of selected fields $stmt = $this->_db->prepare('SELECT password, username, memberID, company FROM tableName WHERE username = :username AND active="Yes" '); $stmt->execute(array('username' => $username)); return $stmt->fetch(); } catch(PDOException $e) { echo '<p class="bg-danger">'.$e->getMessage().'</p>'; } }
3. Step 2: Store Company in the Session
Next, update the login method to save the company value into the session when a user successfully logs in:
public function login($username,$password){ $row = $this->get_user_hash($username); if($this->password_verify($password,$row['password']) == 1){ $_SESSION['loggedin'] = true; $_SESSION['username'] = $row['username']; $_SESSION['memberID'] = $row['memberID']; // Add this line to store company data in the session $_SESSION['company'] = $row['company']; return true; } }
4. Test the Fix
After making these changes, log out and log back in (to refresh the session data), then your <?php echo $_SESSION['company']; ?> line in home.php should display the user's company info correctly.
Bonus Tip
If you anticipate needing more user fields later (like email, phone, etc.), you can either add them to the SELECT statement one by one (best practice, since it's explicit and avoids fetching unnecessary data) or use SELECT * (not recommended for production, as it can break if the table schema changes unexpectedly).
内容的提问来源于stack exchange,提问作者mcstudent

