Codeigniter:将用户名变量添加到会话中

时间:2014-03-13 23:10:20

标签: php codeigniter session

大家好我正在尝试在用户登录时从会话中的users表中添加用户名字段。 会话保存在数据库中 但是我收到了这两条消息:

严重程度:通知
消息:未定义的变量:用户名
文件名:controllers / main.php 行号:43

严重程度:通知
消息:未定义索引:用户名
文件名:controllers / main.php 行号:45

我哪里错了?并且'我整天想弄清楚我错在哪里。 提前谢谢。
这是我的模特:

function getDataProfiloUtente($username) {

    $query = $this->db
            ->where('username', $username)
            ->limit(1)
            ->get('users');
    return $query->row();
}

这是我的控制器:

$utente['records'] = $this->model_users->getDataProfiloUtente($username);
        $data = array(
             'username' => $utente['username'],
             'is_logged_in' => 1
        );

        $this->session->set_userdata($data);

这是我的观点:

<?php echo $this->session->userdata('username'); ?>

2 个答案:

答案 0 :(得分:4)

$query->row();

实际上会返回一个您可以使用的对象(在您的模型中):

return $query->row_array(); //this return an array instead of an object

在您的控制器中:

//notice I removed the ['records'] index when assigning, 
//there's no need to store the result into an array
$utente = $this->model_users->getDataProfiloUtente($username);

然后使用对象或数组表示法访问列/字段:

 //if you use row() in your model
$utente->username;

//or if you used row_array in your model do:
//$utente['username'];

From CI documentation

  

行()

     

此函数返回单个结果行。如果您的查询超过   一行,它只返回第一行。 结果返回为   对象。这是一个用法示例

另请注意您将结果保存到另一个数组中,如果您需要这样做,则必须执行以下操作:

//if use row() and store the result in your array $utente['records']
$utente['records']->username;

或者

//if use row_array() and store the result in your array $utente['records']
$utente['records']['username'];

答案 1 :(得分:0)

在我看来,您正在将数组分配给索引为records的另一个数组,因此要获取您的用户名,您必须这样做:

$data = array(
    'username' => $utente['records']['username'],
    'is_logged_in' => 1
);