Ben
Ben

Reputation: 62494

How to group WHERE clauses with active record?

The below active record code isn't grouping WHERE clauses like I need it to...

        $this->db->where('customers_id',$this->user->getCurrentUserProperty('id'))
        $this->db->like('delivery_name', $this->input->post('search'));
        $this->db->or_like('customers_company', $this->input->post('search'));
        $this->db->or_like('customers_company2', $this->input->post('search'));
        $this->db->or_like('customers_company3', $this->input->post('search'));
        $this->db->or_like('customers_company4', $this->input->post('search'));

This generates

WHERE `customers_id` = 31509 AND `delivery_name` LIKE '%str%' OR `customers_company` LIKE '%str%'"

I NEED the output to have parenthesis around it like below... how can I do that?

WHERE `customers_id` = 31509 AND (`delivery_name` LIKE '%str%' OR `customers_company` LIKE '%str%')"

Note: I hate active record for annoying times like this

If I use the below method, how can I sanitize the input so it's not raw into the query?

$where = "name='Joe' AND status='boss' OR status='active'";

$this->db->where($where);

Upvotes: 3

Views: 3414

Answers (2)

Aldiyah
Aldiyah

Reputation: 351

In Codeigniter 3.0.3 you can do it simple like this :

$this->db->where('customers_id',$this->user->getCurrentUserProperty('id'));
$this->db->group_start();
$this->db->like('delivery_name', $this->input->post('search'));
$this->db->or_like('customers_company', $this->input->post('search'));
$this->db->or_like('customers_company2', $this->input->post('search'));
$this->db->or_like('customers_company3', $this->input->post('search'));
$this->db->or_like('customers_company4', $this->input->post('search'));
$this->db->group_end();

Perhaps it can help

Upvotes: 1

gen_Eric
gen_Eric

Reputation: 227310

Unfortunately, there doesn't seem to be a clean way to do this. where accepts a string to be used as the clause, so you can do something like this (yes I know, it's not pretty):

$search = $this->db->escape_like_str($this->input->post('search'));
$this->db->where('customers_id',$this->user->getCurrentUserProperty('id'));
$this->db->where("(`delivery_name` LIKE '%$search%' OR `customers_company` LIKE '%$search%')");

Upvotes: 4

Related Questions