2011-12-16 85 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(); 

这将返回一个基于你设置的用户会话数据的特定行。