3

我的模型中有以下代码:

$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 正在像这样逃避 $filter:

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
4

1 回答 1

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";
于 2012-08-08T13:06:21.080 回答