多个和/或条件在Ci中不起作用

时间:2017-01-06 14:39:01

标签: php sql codeigniter mysqli

我被困在这里,似乎查询是正确的,但我得到了一些不同的结果

SELECT `car_id`, `pickup_date`, `pickup_time`, `drop_date`, `drop_time`, `booking_status`, `pickup_seconds`, `drop_seconds`
FROM `car_booking`
WHERE `pickup_seconds` BETWEEN 1484516700 AND 1484606100
OR `drop_seconds` BETWEEN 1484516700 AND 1484606100
AND `car_id` = '14782'
AND `ride_status` != 'completed'
AND `booking_status` != 'rejected'

我在这里买车,但是他的car_id不是14782,这个车里没有车(14782),我得到其他车的细节。

下面是我的代码

$this->db->select("car_id , pickup_date ,pickup_time ,drop_date ,drop_time,booking_status,pickup_seconds,drop_seconds");

        $this->db->or_where("pickup_seconds BETWEEN $ps AND $ds");
        $this->db->or_where("drop_seconds BETWEEN $ps AND $ds");
        $this->db->where('car_id' , "14782");
        $query1 = $this->db->get_where("car_booking", array("ride_status !="=>"completed","booking_status !="=>"cancelled","booking_status !="=>"rejected"));

任何人都可以建议我吗?

谢谢。

2 个答案:

答案 0 :(得分:1)

$where = "(pickup_seconds BETWEEN '.$ps.' AND '.$ds.' or drop_seconds BETWEEN '.$ps' AND '.$ds.' )"; 

$query = $this
        ->db
        ->select("car_id , pickup_date ,pickup_time ,drop_date,drop_time,booking_status,pickup_seconds,drop_seconds")
        ->from('car_booking')
        ->where($where)
        ->where('car_id' , "14782")
        ->where('ride_status !=' , "completed")
        ->where('booking_status !=',"rejected")
        ->get();


        if($query->num_rows()>0)
        {
            return $query->result();            }
        else {
           return null;
        }

我认为上面的代码是有效的,因为这是我在CodeIgniter项目中实现orwhere条件的方式,因为我没有得到CodeIgniter的orwhere函数的预期结果。如果它不起作用,请评论下面的问题。

答案 1 :(得分:1)

自Codeigniter 3.0起,您可以使用group_start()和group_end()。有关查询分组here

的更多信息

您的示例可能如下所示:

$query = $this->db    ->select("car_id , pickup_date ,pickup_time ,drop_date ,drop_time,booking_status,pickup_seconds,drop_seconds");

                        ->where('car_id' , '14782')
                        ->where('ride_status !=' , 'completed')
                        ->where('booking_status !=', 'rejected')
                        ->group_start()
                            ->where("pickup_seconds BETWEEN $ps AND $ds")
                            ->or_where("drop_seconds BETWEEN $ps AND $ds")
                        ->group_end()
                        ->get('car_booking');
return ($query->num_rows() ) ?$query->result():false;