我在表的主索引上查询一个表,它只会产生一行结果。
$query= $this->db->query('SELECT Name FROM people WHERE PersonID = 1');
现在要访问该"名称",在我看来,我必须始终遍历结果集。
foreach ($query->result() as $row) {
echo $row->Name;
}
是否总是必须遍历结果集?我知道可能有充分的理由,但在所有情况下都是绝对必要的吗?有没有办法直接去类似的东西
echo $query->result()->Name //pseudo code - won't actually work
(这是PHP/CodeIgniter)
$query->first_row()->Name
https://www.codeigniter.com/user_guide/database/results.html
请看一下这两个函数
function _getColumn($table, $column, $where = array()) {
$this->db->select($column);
$q = $this->db->get_where($table, $where);
return ($q->num_rows() > 0) ? $q->result()[0]->$column : FALSE;
}
//after calling this function your result is as follows
var_dump($this->model_name->_getColumn('people', 'name', array('personID' => '1')));
//output
//string(6) "Maxcot" //or BOOLEAN(FALSE)
//also please note that it can not handle as "$column" parameter this input = "id, name"
第二个功能是获取更多列
function _getColumns($table, $column, $where = array()) {
$this->db->select($column);
$this->db->where($where);
$q = $this->db->get($table);
return ($q->num_rows() > 0) ? $q->result()[0] : FALSE;
}
//after calling function like this
$person_info = $this->model_name->_getColumn('people', 'name, address, phone', array('personID' => '1'));
//you can access table columns like this (also check if $person_info is not FALSE)
$person_info->name;// ->address, ->phone
尝试$this->db->query('...')->fetchObject()->Name
因为fetch
返回数组
更新:代码适用于PDO,因为代码点火器可以使用
$this->db->query('...')->result()->Name