Select only one column from multiple rows in Codeigniter
Asked Answered
G

2

6

I'm thinking about efficiency, and I'm not really sure about it one way or another.

But I have a bunch of rows with multiple columns. I just need the name field from all the rows where a certain other key is a certain value. I can get all these rows like this:

$this->db->where('res_id', $res_id);
$q = $this->db->get('products');
return $q->result();

then i can foreach through the array that it returns and only use name method of each object liek this:

foreach($returned_value as $fun):
    echo $fun->name;
endforeach;

But I'm wondering, would it be more efficient to only select the name attribute from each row, and I feel stupid asking it cause I've been using active record forever, but how would I go about this. I realize I could write it out using the $this->db->query() function, but is there a way to specify it using the main active record commands?

Gand answered 8/8, 2012 at 22:34 Comment(0)
L
10
    $this->db->select('name'); 
    $this->db->from('tblNAME');   
    $this->db->where('res_id', $res_id);
    return $this->db->get()->result();

It is quicker and more efficient I suppose as you are not returning everything.

UNTESTED

Here is a tested function I use which you might find good reeference

function get($id = null) 
        {
            $this->db->select('id, Username, First_Name, Last_Name, Role, Email');
            $this->db->from('user');
            if (!is_null($id)) $this->db->where('id', $id);
            $this->db->order_by('id', 'desc');
            return $this->db->get()->result();
        }
Lampedusa answered 8/8, 2012 at 22:39 Comment(0)
M
0

Neither CI3 nor CI4 offer an active record method to isolate a column of data from a query's result set. The sleekest you can program it would be to callarray_column() on the 2d result set.

public function getProductNamesById(int $res_id): array
{
    return array_column(
        $this->db->select('name')
                 ->get_where('products', ['res_id', $res_id])
                 ->result(),
        'name'
    );
}
Mundane answered 19/3, 2024 at 12:2 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.