phpcodeignitermodel-view-controllerwhere-clausequery-builder

How to pass query filtering conditions from controller to model and use CodeIgniter's query builder


I'm not sure if it's right or wrong, but I want to use below where clauses. I'm following Codeigniter manual (chapter Active Record Class, section $this->db->where();, point 4) Custom string).

$condition = uid = '4' AND id = '1';

My Controller

$fields = "id";
$condition = "";
if ($condition) { 
    $condition .= " AND ";
}
if ($json_decoded->userId) { 
    if ($condition) { 
        $condition .= " AND ";
    }
    $condition .= " uid = '" . $json_decoded->userId . "'";
}
if ($json_decoded->listId) { 
    if($condition) { 
        $condition .= " AND ";
    }
    $condition .= " id = '" . $json_decoded->listId . "'";
}
$checkExist = $this->mdl_details->getDetailByIdandUid($fields, $condition);
  1. My Model function
$this->db->select($fields);

$this->db->from(TBL_DETAILS);

if (!empty($condition)) { 
    $this->db->where($condition);
}

$query = $this->db->get()->row();
return $query;

It shows me error as bellow

Error Number: 1054

Unknown column ' uid = '4' AND id = '1'' in 'where clause'

SELECT `id` FROM (`guide`) WHERE ` uid = '4' AND id = '1'

How can I get rid of this backtick (`) character in the query?


Solution

  • Pass 'FALSE' as third parameter in $this->db->where(), then codeigniter will not add backticks.

    $this->db->where('MATCH (field) AGAINST ("value")', NULL, FALSE);
    

    In your case

    $this->db->where($condition, NULL, FALSE);