2017-10-07 46 views
0
$this->db->select(); 
$this->db->from('demo'); 
$this->db->where('city',html_escape($this->input->post('input',TRUE))); 
$this->db->where('name',$a); 
// if $a = "none" then no where clause with $a 
// if $a != "none" then apply where clause with $a 

$this->db->where('car',$b); 
// what was tried -> if..else 
// e.g if ($a == "none") { 
// } else { 
// $this->db->where('name',$a); 
// } 
// if condition works till above line, but then it fails to generate proper query string 
// in below $c variable 
// e.g if ($c == "none") { 
// } else { 
// $this->db->where('bike',$c); 
// } 

$this->db->where('bike',$c); 
// if $c = "none" then no where clause with $c 
// if $c != "none" then apply where clause with $c 
$this->db->where('status', $d); 
$this->db->order_by('price','desc'); 
$this->db->limit(25,0); 
// echo $this->db->get_compiled_select(); 

處理相同的變量的不同的輸入笨條件邏輯(的if..else)是否有任何簡單的方法做到這一點以線性方式,包括上述條件的邏輯,或一個具有手動構建查詢字符串。用於查詢構建器

編輯1:如果我刪除if..else條件查詢按預期運行。

+0

在您所說的您所評論的代碼中'如果$ a =「none」,那麼沒有where子句與$ a'。你期望與「查詢」是一起還是在查詢之前已經建立? – Vickel

+0

只需將查詢行放置在條件語句中 –

+0

在查詢之前建立@Vickel $ a,因此在構建查詢時,我們獲得的信息是$ a的值。 ($ a通過POST方法輸入) – msinfo

回答

1

是有,你可以隨時隨地在在查詢生成器中添加條件邏輯:

if($a){ 
    $this->db->where('name',$a); 
} 

if (isset($a)){ 
    $this->db->where('name',$a); 
} 

if (!$a==null){ 
    $this->db->where('name',$a); 
} 

或組合以上...

+2

確認消息後,我再次檢查,並可以發現實際的罪魁禍首是錯誤的數據類型比較if條件(0作爲字符串,而不是int) 。現在它工作正常。謝謝。 – msinfo