2011-12-16 77 views
18

假設我有一個包含三列的數據庫表:ID,名稱和年齡。 我需要找到具有特定(唯一)ID的用戶,然後返回年齡。目前,我正在使用以下代碼

$this->db->where('id', '3'); 
$q = $this->db->get('my_users_table'); 

我該如何着手獲取此用戶的年齡?我想我必須使用

$q->result() 

但不知道如何使用它與一行。

+0

可能重複的[CodeIgniter - 只返回一行?](http://stackoverflow.com/questions/4280235/codeigniter-return-only-one-row) – Shomz 2016-03-04 23:37:00

回答

51

解決方案的一個

$this->db->where('id', '3'); 
// here we select every column of the table 
$q = $this->db->get('my_users_table'); 
$data = $q->result_array(); 

echo($data[0]['age']); 

解法

// here we select just the age column 
$this->db->select('age'); 
$this->db->where('id', '3'); 
$q = $this->db->get('my_users_table'); 
$data = $q->result_array(); 

echo($data[0]['age']); 

解決方法三

$this->db->select('age'); 
$this->db->where('id', '3'); 
$q = $this->db->get('my_users_table'); 
// if id is unique, we want to return just one row 
$data = array_shift($q->result_array()); 

echo($data['age']); 

解決方法四(NO活動記錄)

$q = $this->db->query('SELECT age FROM my_users_table WHERE id = ?',array(3)); 
$data = array_shift($q->result_array()); 
echo($data['age']); 
+0

謝謝,它的工作原理:) 是否有更多有效的方式來做到這一點雖然? – Ayub 2011-12-16 23:21:11

6

你可以使用行(),而不是結果()。

$this->db->where('id', '3'); 
$q = $this->db->get('my_users_table')->row(); 
1

訪問單行

//Result as an Object 
$result = $this->db->select('age')->from('my_users_table')->where('id', '3')->limit(1)->get()->row(); 
echo $result->age; 

//Result as an Array 
$result = $this->db->select('age')->from('my_users_table')->where('id', '3')->limit(1)->get()->row_array(); 
echo $result['age']; 
0

您只需在一排使用。

$query = $this->db->get_where('mytable',array('id'=>'3')); 
0

櫃面你是動態獲取的數據,例如當你根據用戶登錄通過他們的ID使用考慮了無活動記錄下面的代碼示例需要的數據:

$this->db->query('SELECT * FROM my_users_table WHERE id = ?', $this->session->userdata('id')); 

return $query->row_array(); 

這將返回一個基於你設置的用戶會話數據的特定行。