Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select only one column from multiple rows in codeigniter. How to and is this more efficient?

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? Thanks.

like image 203
Rooster Avatar asked Aug 08 '12 22:08

Rooster


1 Answers

    $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();
        }
like image 151
1321941 Avatar answered Sep 20 '22 22:09

1321941