数据库查询中LIKE的诡异现象
发现这么一个问题:$this->db-like("name","(");
$this->db->get("test");
这个能够获取到结果
但是如果改成
$str = "(";
$this->db->like("name",$str);
$this->db->get("test");
这段代码确无法获取结果,并且追根溯源一直到mysql_query($sql,$this->conn_id)这个最根本的语句,把$sql输出出来,发现两段代码最终的SQL语句是完全一样的,但是就是结果不一样。这是什么道理?谢谢! 貌似单引号和双引号的区别。 回复 2# spt119
但是这个$str是我从URL获取来的,如
function search($str){
$this->db->like("name",$str);
$query = $this->db->get("test");
}
这个地方还是没有结果,应该怎么处理才能获取到呢? 字符串一样,结果不一样,只能是见鬼了。。。。
我认为肯定有不一样的地方。 回复 4# Hex
不可思议的事情诞生了。。。
这个是我的代码
function search2($keyword = '')
{
$query = $this->db->query("select * from product where name like '%(2,4-difluorophenyl)%'");
print_r($query->result());
echo "<br/>";
//$query = $this->db->get("product");
$query = $this->db->query("select * from product where name like '%".$keyword."%'");
print_r($query->result());
echo "<br/>";
}
其中在mysql_driver.php中的_execute函数中打印SQL语句:
function _execute($sql)
{
$sql = $this->_prep_query($sql);
echo $sql."<br/>";
return @mysql_query($sql, $this->conn_id);
}
最后的结果为
select * from product where name like '%(2,4-difluorophenyl)%'
Array ( => stdClass Object ( => 360 => 2-(2,4-difluorophenyl)cyclopropanecarboxylic acid => 34 => 7 => C10H8F2O2 => => => 198.17 => Zeros000733 => 201007/1278119381MkRWzW.GIF => 97 => => => => 1277186767 ) )
select * from product where name like '%(2,4-difluorophenyl)%'
Array ( ) 回复 5# pillar
两条SQL语句完全一样,但是得到了不同的结果。所以,我怀疑是mysql_result.php这个类里面对Result进行赋值的时候作了处理 那你就跟踪一下程序。
不过我这里一直都是正常的,没发现有这种情况,不排除你的环境问题。 终于解决了。在CI的URI中会进行过滤,将编程字符过滤掉,其中包括以下五个
$, (, ), %28, %29
所以在URI获取$str的时候,CI已经将(转转变成(所以在进行数据库搜索的时候查不到结果,但是显示在浏览器中没有任何差别。
可以用var_dump查看(与(的区别。感谢Hex的帮助!
function _filter_uri($str)
{
if ($str != '' && $this->config->item('permitted_uri_chars') != '' && $this->config->item('enable_query_strings') == FALSE)
{
// preg_quote() in PHP 5.3 escapes -, so the str_replace() and addition of - to preg_quote() is to maintain backwards
// compatibility as many are unaware of how characters in the permitted_uri_chars will be parsed as a regex pattern
if ( ! preg_match("|^[".str_replace(array('\\-', '\-'), '-', preg_quote($this->config->item('permitted_uri_chars'), '-'))."]+$|i", $str))
{
show_error('The URI you submitted has disallowed characters.', 400);
}
}
// Convert programatic characters to entities
$bad = array('$', '(', ')', '%28', '%29');
$good = array('$', '(', ')', '(', ')');
return str_replace($bad, $good, $str);
}
页:
[1]