phpcodeigniteractiverecordconditional-statementsmethod-chaining

How to avoid writing two CodeIgniter active record queries when a WHERE clause is only conditionally needed


I have to execute a query checking if a variable is empty or not. like:

if ($symbol == "") {
    $data_array = $this->db
        ->select('*')
        ->select_max('date')
        ->get('company')
        ->row_array();                  
} else {
    $data_array = $this->db
        ->select('*')
        ->select_max('date')
        ->where('symbol',$symbol)
        ->get('company')
        ->row_array();
}

How can I make it into a single query when I need conditional method chaining?


Solution

  • I think you can do it like this:

    if($symbol == ""){
        $where  = "symbol != 0"; ##$where  = "symbol != ''"; whichever suits your case
    }else{
        $where  = "symbol = '".$symbol."'";
    }
    
    $data_array = $this->db->select('*')
                        ->select_max('date')
                        ->where($where, false, false)
                        ->get('company')
                        ->row_array();