2012-08-08 115 views
3

我在我的模型下面的代碼:CodeIgniter的數據庫查詢

$sql = "SELECT t1.*, t2.* FROM Table1 t1 INNER JOIN Table2 t2 ON t1.id = t2.id AND t2.title IN (?) AND t1.type = ? ORDER BY t1.id"; 
$q = $this->db->query($sql, array($filter, $type)); 

的問題是,這個查詢工作正常,如果:

$filter = 'a'; 

但返回咱這:

$filter = "'a','b','c','d'"; 

因爲我可以看到,CI是逃避$過濾器這樣的第二種情況:

SELECT t1.*, t2.* FROM Table1 t1 INNER JOIN Table2 t2 ON t1.id = t2.id AND t2.title IN ('\'a\',\'b\',\'c\',\'d\'') AND t1.type = ? ORDER BY t1.id 
+0

這是正確的行爲。 CI在將它們發送到MySQL之前會轉義引號。你應該使用一個數組作爲過濾器,並構建如下所示: db-> query('... AND t2.title IN(?,?,?,?)...',$ filter); 如果你需要一個完整的代碼,告訴我。 – 2012-08-08 12:59:08

回答

2

這是正確的行爲。 CI在將它們發送到MySQL之前會轉義引號。你或許應該使用數組用於過濾和構建這樣的事情(未測試))

$filter = array('a','b','c'); 
$sql = "SELECT t1.*, t2.* 
    FROM Table1 t1 
    INNER JOIN Table2 t2 
     ON t1.id = t2.id 
     AND t2.title IN (". implode(',', array_fill(0, count($filter), '?')).") 
     AND t1.type = ? 
    ORDER BY t1.id"; 
//edit: check if $filter is not an array (when it is a single value string) 
$filter = is_array($filter) ? $filter : array($filter); 
$q = $this->db->query($sql, array_merge($filter, array($type))); 

你也應該重寫查詢了一下:

$sql = "SELECT t1.*, t2.* 
    FROM Table1 t1 
    INNER JOIN Table2 t2 
     ON t1.id = t2.id 
    WHERE 
     t2.title IN (". implode(',', array_fill(0, count($filter), '?')).") 
     AND t1.type = ? 
    ORDER BY t1.id"; 
+0

感謝@Patrick它與我已添加到您的答案的一個輕微修改。 '$ filter = is_array($ filter)? $ filter:array($ filter);' – 2012-08-08 14:51:02

+0

不錯,不客氣:) – 2012-08-08 15:04:33