SQL中Codeigniter中的条件

时间:2017-11-13 12:34:35

标签: php sql codeigniter

我想检查预订是否存在。我有入住日期,结账日期和房间号码。我尝试了下面的查询,但它提供了所有不属于该房间ID的数据。我做错了什么?

$array = array('checkin_date' => $checkin, 'checkout_date' => $checkin);
$array1 = array('checkin_date >' => $checkin, 'checkout_date <' => $checkin);
$array2 = array('checkin_date <' => $checkin, 'checkout_date >' => $checkin);
$array3 = array('checkin_date <' => $checkin, 'checkout_date <' => $checkin);
$array4 = array('checkin_date >=' => $checkin, 'checkout_date <=' => $checkin);
$array5 = array('checkin_date >=' => $checkout, 'checkout_date <=' => $checkout);

$this->db->select('*');
$this->db->from('igc_room_booking');
$this->db->where('delete_status', 0);
$this->db->where('cancel_status', 0);
$this->db->where('room_id', $val->room_id);
$this->db->where($array);
$this->db->or_where($array2);
$this->db->or_where($array3);
$this->db->or_where($array);
$this->db->or_where($array4);
$this->db->or_where($array5);
$bookingss = $this->db->get()->result();

3 个答案:

答案 0 :(得分:0)

现在我不是在考虑你的逻辑 - 因为Simos Fasouliotis在评论中说得足够 - 所以你在语法上得到了正确的想法......

但是,如果使用get_compiled_select编译查询,则会得到以下结果:

SELECT *
FROM `igc_room_booking`
WHERE `delete_status` =0
AND `cancel_status` =0
AND `room_id` = 12
AND `checkin_date` = '2010-09-01'
AND `checkout_date` = '2010-09-01'
OR `checkin_date` < '2010-09-01'
OR `checkout_date` > '2010-09-01'
OR `checkin_date` < '2010-09-01'
OR `checkout_date` < '2010-09-01'
OR `checkin_date` = '2010-09-01'
OR `checkout_date` = '2010-09-01'
OR `checkin_date` >= '2010-09-01'
OR `checkout_date` <= '2010-09-01'
OR `checkin_date` >= '2010-10-01'
OR `checkout_date` <= '2010-10-01'

到现在你应该能够理解这个问题是什么......

可能的解决方案可能是

$bookingss = $this->db
    ->select('*')
    ->from('igc_room_booking')
    ->where('delete_status', 0)
    ->where('cancel_status', 0)
    ->where('room_id', $val->room_id)
    ->group_start()
        ->or_where($array)
        ->or_where($array2)
        ->or_where($array3)
        ->or_where($array4)
        ->or_where($array5)
    ->group_end()
    ->get()
    ->result();

但imho没有任何意义,你应该清楚地考虑你需要哪个日期范围......

答案 1 :(得分:0)

试试这个:

$array = "('$checkindate' BETWEEN `checkin_date` AND `checkout_date`) OR  ('$checkoutdate' BETWEEN `checkin_date` AND `checkout_date`) OR (`checkin_date` > '$checkindate' AND `checkout_date` < '$checkoutdate')";
    $this->db->select('*');
    $this->db->from('igc_room_booking');
    $this->db->where('delete_status', 0);
    $this->db->where('cancel_status', 0);
    $this->db->where('room_id', $val->room_id);
    $this->db->where($array);
    $bookingss = $this->db->get()->result();

答案 2 :(得分:-1)

我认为问题是您的查询错误....您应该删除

  

$ this-&gt; db-&gt; select(*)and $ this-&gt; db-&gt; from(&#39; igc_room_booking&#39;)

,而在你所有的where子句之后,你应该有

  

$这 - &GT; DB-&GT;获得(&#39; igc_room_booking&#39);