PHP Session只存储一个值

时间:2011-12-15 03:10:52

标签: php postgresql session

function StoreUserProfileInSession( $username, $password )
{
        session_start();
        $query = pg_query( "SELECT * FROM mytable where username = '$username' AND password = '$password'" );

        $rows = pg_fetch_array( $query );

        foreach( $rows as $key => $value )
        {
            if( $key == 'password' ) //do not store password in session because it's DANGEROUS!
                continue;

            $_SESSION[$key] = $value;
        }
}

在调用此功能后,我被重定向到我的前端 当我在那里尝试print_r($_SESSION);时,我在会话中只有一个值,那就是user_id,我的表中有很多字段。
为什么我只获得一个价值?这有什么问题?

任何帮助或想法都将受到极大的赞赏和奖励! 谢谢! :)

3 个答案:

答案 0 :(得分:5)

两件事:

  1. pg_fetch_array()没有回复您的期望。
  2. $_SESSION 不能拥有任何不能成为php变量名称的密钥名称
  3. $rows看起来像这样:

    $rows = array(
        'user_id' => 1
        1,
        'password' => 'THE PASSWORD',
        'THE PASSWORD',
    );
    $rows['user_id'] === $rows[0];
    // etc
    

    因此,在你的foreach循环中,在user_id键之后,你实际上是这样做的:

    $_SESSION[0] = 1;
    

    这是非法的,因此会话对象停止工作。

    而是这样做:

    // PGSQL_ASSOC says, "only return named keys, not numeric keys"
    $therow = pg_fetch_array($query, null, PGSQL_ASSOC);
    unset($therow['password']);
    $_SESSION['user'] = $therow;
    pg_free_result($query);
    
    
    // get user data like this:
    $_SESSION['user']['user_id']
    

答案 1 :(得分:1)

也许这是因为你在执行查询后只得到一行?

返回的行数为:

"SELECT * FROM mytable where username = '$username' AND password = '$password'"

答案 2 :(得分:0)

感谢您的回答。我设法通过这样做来回答它。

function StoreUserProfileInSession( $username, $password )
    {
        session_start();
        $query = pg_query( "SELECT * FROM mytable where username = '$username' AND password = '$password'" );
        $fields = array();

        while( $rows = pg_fetch_array( $query ) )
        {
            $fields[] = $rows;
        }

        foreach( $fields[0] as $key => $value )
        {
            if( is_int( $key ) || $key == 'password' )
                continue;
            $_SESSION[$key] = $value;
        }
    }