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

时间:2015-02-11 11:39:38

标签: codeigniter codeigniter-datamapper

如何在代码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'

我没有将param值放在查询中并使用如下所示: $ query =' SELECT mycol from mytable WHERE name LIKE'%foo';

我也不能使用$ this-> db-> like()函数,因为我的查询包含: INSERT IGNORE 和 INSERT INTO表SELECT col FROM table2;

请建议? 谢谢,

3 个答案:

答案 0 :(得分:2)

只需使用CodeIgniter查询生成器

$name = 'foo';

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

答案 1 :(得分:1)

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

答案 2 :(得分:1)

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));