【问题标题】:Codeigniter: Add username variable to the sessionCodeigniter:将用户名变量添加到会话中
【发布时间】:2014-03-13 23:10:19
【问题描述】:

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

严重性:通知
消息:未定义变量:用户名
文件名:控制器/main.php 行号:43

严重性:通知
消息:未定义索引:用户名
文件名:控制器/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'); ?>

【问题讨论】:

    标签: php codeigniter session


    【解决方案1】:

    这个

    $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
    • 现在我收到以下错误: 严重性:通知消息:未定义的变量:用户名文件名:控制器/main.php 在查看此错误时:严重性:通知消息:数组到字符串转换文件名:views / members.php 行号:50
    • 根据您的建议,我在模型中使用 row_array () 并在控制器中使用此代码: $ user ['username'] = $ this-> model_users-> getDataProfiloUtente ($ username); $ data = array ('username' => $ user ['username'], 'is_logged_in' => 1); $ this-> session-> set_userdata($data);
    • 对不起,这是正确的代码:$utente['username'] = $this->model_users->getDataProfiloUtente($username); $data = array('username' => $utente['username'], 'is_logged_in' => 1); $this->session->set_userdata($data);
    • Change 'username' =&gt; $utente['username'],to 'username' =&gt; $utente['username']['username'] 你仍然将模型的结果保存到数组位置 ($user['username']) 你不需要这样做(至少你想要或有这个要求),我确实用这些细节更新了我的答案。
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2013-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-29
      • 2017-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多