Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Codeigniter select query with AND and OR condition

Tags:

codeigniter

I want a Codeigniter select query from a table with three conditions in .

1. wrk_fld_exc = 140
2. wrk_cs_sts = Open
3. wrk_dlvrd_sts = Delivered OR wrk_cl_sts = Success

The third condition is an AND condition contains OR condition. First and second is And condition.

like image 757
keerthi Avatar asked Mar 30 '12 10:03

keerthi


4 Answers

I want to add some info for Codeigniter 3.1.11:

There is a Query grouping in Query Builder Class

So Ben Answer will be like this:

public function some_function()
    {
        $this->db->where("wrk_fld_exc",140);
        $this->db->where("wrk_cs_sts","Open");
        $this->db->group_start();
        $this->db->where("wrk_dlvrd_sts","Delivered");
        $this->db->or_where("wrk_cl_sts","Success");
        $this->db->group_end();
        return $this->db->get("some_table");
    }

After check with:

        echo $this->db->last_query();

It will produce SQL:

SELECT * FROM `some_table` WHERE `wrk_fld_exc` = 140 AND `wrk_cs_sts` = 'Open' AND ( `wrk_dlvrd_sts` = 'Delivered' OR `wrk_cl_sts` = 'Success' )

Further Read: Codeigniter Manual Book

like image 181
sukalogika Avatar answered Oct 05 '22 04:10

sukalogika


You can code it like this:

       $this->db->where('wrk_fld_exc',140);
       $this->db->where('wrk_cs_sts','open');
       $where = '(wrk_dlvrd_sts="open" or wrk_cl_sts = "Success")';
       $this->db->where($where);
like image 25
Ben Avatar answered Oct 05 '22 02:10

Ben


codeigniter uses its own syntax for OR claus in query

$this->db->or_where('wrk_cl_sts','Success'); 

to use AND in where clause use $this->db->where(''); twice

like image 28
iCodeCrew Avatar answered Oct 05 '22 02:10

iCodeCrew


Like this

 $this->db->where('wrk_fld_exc',140);
 $this->db->where('wrk_cs_sts','open');
 $this->db->where('wrk_dlvrd_sts ','Delivered');
 $this->db->or_where('wrk_cl_sts','Success');
like image 40
Cristiana Chavez Avatar answered Oct 05 '22 02:10

Cristiana Chavez