php Codeigniter $this->db->get(),如何返回特定行的值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8541291/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Codeigniter $this->db->get(), how do I return values for a specific row?
提问by Ayub
Say I have a database table with three columns: ID, Name, and Age. I need to find the user with a specific (unique) ID, and then return the age. Currently, I am using the following code
假设我有一个包含三列的数据库表:ID、Name 和 Age。我需要找到具有特定(唯一)ID 的用户,然后返回年龄。目前,我正在使用以下代码
$this->db->where('id', '3');
$q = $this->db->get('my_users_table');
How do I go about getting the age for this user? I think I have to use
如何获取此用户的年龄?我想我必须使用
$q->result()
But not sure how to use it with one row.
但不确定如何在一行中使用它。
回答by Dalen
SOLUTION ONE
解决方案一
$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']);
SOLUTION TWO
解决方案二
// 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']);
SOLUTION THREE
解决方案三
$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']);
SOLUTION FOUR (NO ACTIVE RECORD)
解决方案四(无活动记录)
$q = $this->db->query('SELECT age FROM my_users_table WHERE id = ?',array(3));
$data = array_shift($q->result_array());
echo($data['age']);
回答by Doms
you can use row() instead of result().
您可以使用 row() 而不是 result()。
$this->db->where('id', '3');
$q = $this->db->get('my_users_table')->row();
回答by mobby
Accessing a single 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'];
回答by Waseem shah
You simply use this in one row.
您只需在一行中使用它。
$query = $this->db->get_where('mytable',array('id'=>'3'));
回答by David Martin
Incase you are dynamically getting your data e.g When you need data based on the user logged in by their id use consider the following code example for a No Active Record:
如果您正在动态获取数据,例如,当您需要基于通过其 id 登录的用户的数据时,请考虑以下无活动记录的代码示例:
$this->db->query('SELECT * FROM my_users_table WHERE id = ?', $this->session->userdata('id'));
return $query->row_array();
This will return a specific row based on your the set session data of user.
这将根据您设置的用户会话数据返回特定行。