phpcodeigniterwhere-clausequery-buildermethod-parameters

How to process a mix of AND and OR conditions passed to a CodeIgniter model method


I only want to select a specific row/s with user_id = $this->session->id , status = 4 hours, 8 hours and work from home.

EDIT: all my status is

but what happened is it only returns all the Work From Home of the specific user_id and not included the 4 hours and 8 hours status

Controller

$order_by = "id desc";
$where = [
    'user_id' => $this->session->id,
    'status' => '4 hours',
    'status' => '8 hours',
    'status' => 'Work From Home'
];
$this->Crud_model->fetch('record', $where, "", "", $order_by);

MODEL

public function fetch($table, $where = "", $limit = "", $offset = "", $order = "")
{
    if (!empty($where)) {
        $this->db->where($where);   
    }
    if (!empty($limit)) {
        if (!empty($offset)) {
            $this->db->limit($limit, $offset);
        } else {
            $this->db->limit($limit);   
        }
    }
    if (!empty($order)) {
        $this->db->order_by($order); 
    }

    $query = $this->db->get($table);
    if ($query->num_rows() > 0) {
        return $query->result();
    } else {
        return FALSE;
    }
}

Solution

  • Try the following:

    Controller:

    $order_by = "id desc";
    $where = ['user_id' => $this->session->id];
    $where_in = ['name' => 'status', 'values' => ['4 hours', '8 hours', 'Work From Home']];
    $this->Crud_model->fetch('record',$where,"","",$order_by, $where_in);
    

    Model:

    public function fetch($table,$where="",$limit="",$offset="",$order="", $where_in = false){
        if (!empty($where)) {
            $this->db->where($where);   
        }
        if (!empty($limit)) {
            if (!empty($offset)) {
                $this->db->limit($limit, $offset);
            }else{
                $this->db->limit($limit);   
            }
        }
        if (!empty($order)) {
            $this->db->order_by($order); 
        }
    
        if($where_in)
        {
            $this->db->where_in($where_in['name'], $where_in['values']);
        }
    
        $query = $this->db->get($table);
        if ($query->num_rows() > 0) {
            return $query->result();
        }else{
            return FALSE;
        }
    }
    

    This uses where_in functionality to get all records for those status values.