在mysql查询LIKE中使用#%_ +进行搜索
I have this code ( just some part of it) :
<?php
if(isset($_GET['act']) && $_GET['act']== 'do') {
$key= $_POST['key'];
}
else {
$key= '';
}
?>
<input class='inputField' type='text' name='key' size=45 value='<?php echo $key;?>' >
<script>$(document).ready(function(){
key= $("#mainTop input").val();
if(key!= null || key== '%') {
showPage(1,key);
}
else {
showPage(1);
}
});
</script>
The showpage() will get parameter and pass to php file :
if(isset($_GET['key'])) {
$key= addslashes($_GET['key']);
}
else {
$key= null;
}
$result= $db->query("SELECT * FROM information WHERE stuId LIKE '%$key%' OR stuName LIKE '%$key%' LIMIT $start,10");
The php file will get the key to search. I escape the key by addslashes,the do the mysql query to search. But if I search with key = % # _ +,it still print our all the table instead there are no matching result. I guess that I did not escape the key in right way,so how do I escape character such as % # _ + to do mysql query with LIKE ? Please help me out ? I had a look at some another question but I still dont get it
我有这段代码(只是其中的一部分): p>
&lt;?php if(isset($ _ GET ['act'])&amp;&amp; $ _GET ['act'] =='do'){ $ key = $ _POST ['key']; } else { $ key =''; } ?&gt; &lt; input class ='inputField'type ='text'name ='key'tize = 45 value ='&lt ;?php echo $ key;?&gt;' &GT; &lt; script&gt; $(document).ready(function(){ key = $(“#mainTop input”)。val(); if(key!= null || key =='%') { showPage(1,key); } else { showPage(1); } }); &lt; / script&gt; code> pre> \ nshowpage()将获取参数并传递给php文件: p>
if(isset($ _ GET ['key'])){ $ key = addslashes($ _ GET ['key']); } else { $ key = null; } $ result = $ db-&gt; query(“SELECT * FROM information WHERE stuId LIKE'%$ key%'或stuName LIKE'%$ key%'LIMIT $ start,10“); code> pre>
php文件将获得搜索的密钥。 我通过addslashes转义键,执行mysql查询搜索。 但是如果我用key =%#_ +搜索,它仍会打印我们所有的表而不是没有匹配的结果。 我猜我没有逃脱 正确的方法,所以如何逃避%#_ +这样的角色用LIKE做mysql查询? 请帮帮我吗? 我看了一些其他的问题,但我仍然没有得到它 p> div>
As far as I know, #
and +
are not special characters in a LIKE match string, but you simply need to escape the others
$key = str_replace(array('%', '_'), array('\%', '\_'), $key);
A solution to this problem is simply to use parameterized queries.
You wont have to worry about escaping.
You protect yourself from SQL injection.
Your code will be taken more seriously by your peers and people looking to hire you.
Keep in mind that you are dealing with three levels that need to be escaped. E.G. in PHP you must escape '
unless you want it to be interpreted as a quote, the mysql query itself must escape the same '
, manually (\'
) with something like addslashes or using prepared statements, and the regular expression within the mysql query must be escaped if it is a reserved character like %
or _
are in a LIKE
statement.