views:

193

answers:

2

This is my function to get stuff from a SQL db...

Is there a more elegant way to do this?

function getResults_1($id)
{
    $this->db->select(array("a_1","a_2"))->from('Survey');
    $this->db->where('user_id', $id);

    return $this->db->get();
}
function getResults_2($id)
{
    $this->db->select(array("a_6","a_8","a_13","a_14"))->from('Survey');
    $this->db->where('user_id', $id);

    return $this->db->get();
}
and so on... (to 5)...
+2  A: 
function get_results($id, $method) {
    switch($method) {
        case 1: $select = array('a_1','a_2'); break;
        case 2: $select = array('a_6','a_8','a_13','a_14'); break;
        default: $select = false;
    }

    if($select) $this->db->select($select);
    $this->db->where('user_id',$id);

    return $this->db->get('Survey');
}
Steven Xu
+1  A: 

A more optimized (perhaps more convoluted for beginner users) version of @Steven's result. This assumes you don't step out of bounds with the array index reference, otherwise it will error.

function get_results($id, $method) {
    $select_cols = array(1 => array('a_1','a_2'),
                         2 => array('a_6','a_8','a_13','a_14'));
    return $this->db->select($select_cols[$method])
                    ->where('user_id', $id)
                    ->get('Survey');
}
cballou