Ayu*_*yub 20 php sql codeigniter
假设我有一个包含三列的数据库表:ID,Name和Age.我需要找到具有特定(唯一)ID的用户,然后返回年龄.目前,我使用以下代码
$this->db->where('id', '3');
$q = $this->db->get('my_users_table');
Run Code Online (Sandbox Code Playgroud)
我如何为这个用户获取年龄?我想我必须使用
$q->result()
Run Code Online (Sandbox Code Playgroud)
但不知道如何使用它一行.
Dal*_*len 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']);
Run Code Online (Sandbox Code Playgroud)
解决方案二
// 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']);
Run Code Online (Sandbox Code Playgroud)
解决方案三
$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']);
Run Code Online (Sandbox Code Playgroud)
解决方案四(无活动记录)
$q = $this->db->query('SELECT age FROM my_users_table WHERE id = ?',array(3));
$data = array_shift($q->result_array());
echo($data['age']);
Run Code Online (Sandbox Code Playgroud)
小智 6
你可以使用row()而不是result().
$this->db->where('id', '3');
$q = $this->db->get('my_users_table')->row();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
127187 次 |
| 最近记录: |