0

我在它的主索引上查询一个表,它只会产生一行结果。

$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)

4

3 回答 3

0
$query->first_row()->Name

https://www.codeigniter.com/user_guide/database/results.html

于 2013-10-16T10:38:59.967 回答
0

请看看这两个功能

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
于 2013-10-16T01:39:05.347 回答
0

尝试$this->db->query('...')->fetchObject()->Name返回fetch数组

更新:代码适用于 PDO,codeigniter 可以使用

$this->db->query('...')->result()->Name

于 2013-10-15T23:54:52.520 回答