You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP PDO获取数据库指定行问题:无法显示用户company字段

Fixing the Missing Company Info in Your Session

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_hash function only selects password, username, and memberID from the database — it doesn't fetch the company field at all.
  • Even if it did pull the company data, your login function 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:09:59