2014-03-13 58 views
0

大家好我試圖在用戶登錄時在會話中的用戶表添加用戶名字段。 會話保存在數據庫中。
但我得到這兩個消息:Codeigniter:添加用戶名變量到會話

嚴重性:注意
消息:未定義變量:用戶名
文件名:控制器/ 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'); ?> 

回答

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:然後使用對象或數組符號訪問列/場

row()

This function returns a single result row. If your query has more than one row, it returns only the first row. The result is returned as an object. Here's a usage example

還要注意你保存結果到另一個數組,如果你需要做的以這種方式,你將不得不做這樣的事情:

//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']; 
+0

你解釋完美! +1 –

+0

現在我收到以下錯誤: 嚴重性:通知 消息:未定義變量:用戶名 文件名:controllers/main。PHP 同時鑑於此錯誤: 嚴重性:注意 消息:數組字符串轉換 文件名:觀點/ members.php 行號:在模型50 – user3311699

+0

從你的建議,我使用row_array() 和這個代碼在控制器中: $ user ['username'] = $ this-> model_users-> getDataProfiloUtente($ username); $ data = array( 'username'=> $ user ['username'], 'is_logged_in'=> 1 ); $ this-> session-> set_userdata($ data); – user3311699

0

在我看來,你正在將數組分配給另一個數組wi日指標records所以要得到你的用戶名,你必須做到:

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