2012-12-04 61 views
-1

基本上通過顯示一個表單,其中用戶可以輸入2個變量$ no和$ first,但我只能在輸入兩個字段時顯示結果。我需要它的工作,所以當我輸入1個變量時,它會顯示結果。Codeigniter搜索查詢不能正常工作

我想我可以使用某種OR語句,但我不確定如何實現它。任何幫助將不勝感激,我很抱歉,如果它不夠清楚,我談到codeigniter時是相當新的。

控制器

public function query() 

{ 

$no = $this->input->post('no'); 
$first = $this->input->post('first'); 
$this->load->model("test"); 
    $data['query']=$this->test->query($no,$first); 
    $this->load->view('query',$data); 

} 

型號

function query($no, $first) 
{ 

return $query = $this->db->get_where('table', array('no' => $no, 
'first' => $first))->result(); 

} 

查看

<?php foreach($query as $row): ?> 
<tr> 
<td><?php echo $row->no; ?></td> 
<td><?php echo $row->date; ?></td> 
<td><?php echo $row->first; ?></td> 


</tr> 
<?php endforeach; ?> 

回答

1

您可以嘗試準備在where子句第一

function query($no = "", $first = "") 
{ 
$response = array(); 
if($first != "" || $no != ""){ 
    $where = ""; 
    if($no == "") $where = 'first = '.$first; 
    if($first == "") $where = 'no = '.$no; 
    if($first != "" && $no != "") $where = 'no = '.$no.' AND first = '.$first; 
    $fetch = $this->db->where($where)->from('table')->get(); 
    if($fetch->num_rows() > 0) $response = $fetch->result_array(); 
} 
return $response; 
} 

希望我得到你想要的想法。

0

您需要分離出你的WHERE參數:

function query($no, $first) 
{ 
    $this->db->select(); 
    $this->db->from('table'); 
    $this->db->where('no', $no); 

    if (!empty($first)) 
    { 
     $this->db->or_where('first', $first); // or use `and_where` 
    } 
    return $query = $this->db->get()->result(); 
} 

來源:http://ellislab.com/codeigniter/user-guide/database/active_record.html

+0

只有在no等於$ no的情況下才有效,我讀到他需要或者需要的問題。 –

0
function query($no = '%', $first = '%') 
{ 
$this->db->where("'no' = $no OR 'first' = $first"); 
$query = $this->db->get('table'); 
if($query->num_rows() >= 0) 
{ 
    $return $query->result(); 
} 
} 

如果你喂值的通配符爲默認值或者可以是空的(其實都可以是空的,返回的結果)然後就構建整個地方雙引號內聲明。

如果你不想返回所有的結果如果字符串是空的,你真的不必餵養通配符,但你應該做一些檢查空的結果或沒有回報的地方。