如何在带有绑定参数的代码 iginiter query() 中使用 like 子句?

How to use like clause in code iginiter query() WITH BIND PARAMS?

如何在代码 iginiter query() WITH BIND PARAMS 中使用 like 子句?

例如: 当我使用

$query = 'SELECT mycol FROM mytable WHERE name LIKE %?';
$name = 'foo';
$db->this->query($query,array($name));
//the clause generated
//SELECT mycol FROM mytable WHERE id LIKE '%'foo'%' 
//I expected this
//SELECT mycol FROM mytable WHERE id LIKE '%foo'

我不会将参数值放入查询中并像下面这样使用: $query = 'SELECT mycol FROM mytable WHERE name LIKE '%foo';

我也不能使用 $this->db->like() 函数,因为我的查询包括: 插入忽略 和 INSERT INTO table SELECT col FROM table2;

请指教? 谢谢,

$query = 'SELECT mycol FROM mytable WHERE name LIKE ?';
$name = '%foo';
$this->db->query($query,array($name));

codeigniter 会将 ? 替换为 'params' 值。 如果你写这个

 $query = 'SELECT mycol FROM mytable WHERE name LIKE %?';
 $name = 'foo';
 //$db->this->query($query,array($name)); //you wrote this line wrong.
 //it should be like this
  $this->db->query($query,array($name));

它将产生

SELECT mycol FROM mytable WHERE name LIKE %'foo' //inverse comma after % ,actually before and after foo.

所以你的正确做法是

 $query = 'SELECT mycol FROM mytable WHERE name LIKE ?';
 $name = '%foo';    
 $this->db->query($query,array($name));

它将产生

SELECT mycol FROM mytable WHERE name LIKE '%foo'

注意
你写错了

$db->this->query($query,array($name));

正确的方式

 $this->db->query($query,array($name));

只需使用 CodeIgniter 查询生成器

$name = 'foo';

$query = $this
    ->db
    ->select('mycol')
    ->like('name', $name)
    ->get('mytable');