Codeigniter $ this-> db-> get(),如何返回特定行的值?

时间:2011-12-16 23:15:52

标签: php sql codeigniter

假设我有一个包含三列的数据库表:ID,Name和Age。 我需要找到具有特定(唯一)ID的用户,然后返回年龄。目前,我使用以下代码

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

如何获得此用户的年龄?我想我必须使用

$q->result()

但不确定如何将它用于一行。

5 个答案:

答案 0 :(得分:55)

解决方案一

$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']);

解决方案四(无活动记录)

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

答案 1 :(得分:6)

你可以使用row()而不是result()。

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

答案 2 :(得分: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'];

答案 3 :(得分:0)

您只需在一行中使用它。

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

答案 4 :(得分:0)

如果您正在动态获取数据,例如,当您需要基于用户ID登录的用户的数据时,请考虑以下代码示例为无活动记录:

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

 return $query->row_array();

这将根据您设置的用户会话数据返回特定行。