Welcome Guest, Not a member yet? Register   Sign In
Less redundancy
#1

[eluser]xerosis[/eluser]
This is my first posting on the forum, I have just recently started using codeigniter and it is great but I need some help on the below:

Basically I have written a code that works but I would like to make the redundancy much less and I am sure there is a better way rather than writing so many if cases (perhaps a for loop that can manage it) to do the following (the qualification section especially):

Code:
function GetUsers($options = array())
    {
        // Qualification
        if(isset($options['id']))
            $this->db->where('id', $options['id']);
            
        if(isset($options['firstname']))
            $this->db->where('firstname', $options['firstname']);
            
        if(isset($options['lastname']))
            $this->db->where('lastname', $options['lastname']);
        
        if(isset($options['email']))
            $this->db->where('email', $options['email']);
        
        if(isset($options['password']))
            $this->db->where('password', $options['password']);

    // limit / offset
    if(isset($options['limit']) && isset($options['offset']))
        $this->db->limit($options['limit'], $options['offset']);
    else if(isset($options['limit']))
        $this->db->limit($options['limit']);
            
    // sort
    if(isset($options['sortBy']) && isset($options['sortDirection']))
        $this->db->order_by($options['sortBy'], $options['sortDirection']);
        
    if(!isset($options['status'])) $this->db->where('status !=', 'deleted');
    
    $query = $this->db->get("user");
    
    if(isset($options['count'])) return $query->num_rows();
    
    if(isset($options['id']) || isset($options['email']))
        return $query->row(0);
        
    return $query->result();
#2

[eluser]wiredesignz[/eluser]
Something like:
Code:
foreach (array('id','firstname','lastname','email','password') as $field) {
   if (isset($options[$field])) $this->db->where($field, $options[$field]);
}
...
#3

[eluser]xerosis[/eluser]
Thanks a lot,

This is perfect.




Theme © iAndrew 2016 - Forum software by © MyBB