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


Codeigniter $this->db->get(), how do I return values for a specific row?

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

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

如何获取该用户的年龄?我想我必须使用

$q->result()

但是不知道如何在一行中使用

解决方案一个

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

可以用row()代替result()

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

访问单行

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

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

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

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

您只需在一行中使用它。

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