我的模型中有以下代码:
$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
答案 0 :(得分: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";