2017-01-24 64 views
0

我定義了一個模型並試圖使用UNION關鍵字從兩個表中獲取數據。在這裏,我使用LIKE關鍵字作爲約束條件。當我使用這個沒有變量的查詢(硬編碼變量值)時,它可以工作。但它不適用於變量。相反,它提供了一個空數組。它出什麼問題了?帶有CodeIgniter變量的MySQL LIKE子句

function searchProf(){ 
    //$name=$this->input->post('name'); 
    $name='du'; 
    $query=$this->db->query("SELECT name FROM users WHERE name like '%".$name."%' UNION SELECT name FROM children WHERE name like '%".$name."%' "); 
    print_r ($query->result()); 

} 

回答

0

'%".$name."%'更改爲此'%$name%'


function searchProf(){ 
    //$name=$this->input->post('name'); 
    $name ='du'; 
    $query = $this->db->query("SELECT name FROM users WHERE name like '%$name%' UNION SELECT name FROM children WHERE name like '%$name%' "); 
    print_r ($query->result());  
} 
0

請使用主動備案基地或SQL綁定到您的SQL查詢。否則,你必須面對SQL注入。

`

function searchProf(){ 
    $name ='du'; 
    $sql = "SELECT name FROM users WHERE name like ? UNION SELECT name FROM children WHERE name like ? "; 
    $query = $this->db->query($sql,array('%'.$name.'%','%'.$name.'%')); 
    print_r ($query->result());  
}