[英]mysql like statement is not working as expected
I have a table with 4 record. 我有一张4条记录的桌子。
Records: 1) arup Sarma
2) Mitali Sarma
3) Nisha
4) haren Sarma
And I used the below SQL statement to get records from a search box. 我使用下面的SQL语句从搜索框中获取记录。
$sql = "SELECT id,name FROM ".user_table." WHERE name LIKE '%$q' LIMIT 5";
But this retrieve all records from the table. 但是这会从表中检索所有记录。 Even if I type a non-existence word (eg.: hgasd or anything), it shows all the 4 record above.
即使我键入一个不存在的单词(例如:hgasd或任何东西),它也会显示上面的所有4条记录。 Where is the problem ?
问题出在哪儿 ? plz any advice..
请问任何建议..
This is my full code: 这是我的完整代码:
$q = ucwords(addslashes($_POST['q']));
$sql = "SELECT id,name FROM ".user_table." WHERE name LIKE '%".$q."' LIMIT 5";
$rsd = mysql_query($sql);
Your query is fine. 你的查询没问题。 Your problem is that $q does not have any value or you are appending the value incorrectly to your query, so you are effectively doing:
您的问题是$ q没有任何值,或者您将错误的值附加到查询中,因此您实际上是这样做的:
"SELECT id,name FROM ".user_table." WHERE name LIKE '%' LIMIT 5";
Use the following code to 使用以下代码
A - Prevent SQL-injection A - 防止SQL注入
B - Prevent like with an empty $q B - 防止像空的$ q一样
//$q = ucwords(addslashes($_POST['q']));
//Addslashes does not work to prevent SQL-injection!
$q = mysql_real_escape_string($_POST['q']);
if (isset($q)) {
$sql = "SELECT id,name FROM user_table WHERE name LIKE '%$q'
ORDER BY id DESC
LIMIT 5 OFFSET 0";
$result = mysql_query($sql);
while ($row = mysql_fetch_row($result)) {
echo "id: ".htmlentities($row['id']);
echo "name: ".htmlentities($row['name']);
}
} else { //$q is empty, handle the error }
A few comments on the code. 关于代码的一些评论。
$vars
you inject into the code with single '
quotes. $vars
你注入与单一的代码'
行情。 If you don't the escaping will not work and syntax error will hit you. isset
to see if it's filled. isset
测试var以查看它是否已填充。 order by
clause so the outcome will not be random, here I've order the newest id, assuming id
is an auto_increment field, newer id's will represent newer users. order by
子句,所以结果不会是随机的,这里我订购了最新的id,假设id
是auto_increment字段,较新的id将代表更新的用户。 htmlentities
to prevent XSS security holes. htmlentities
转义该数据以防止XSS安全漏洞。 In mysql, like operator use '$' regex to represent end of any string.. and '%' is for beginning.. so any string will fall under this regex, that's why it returms all records. 在mysql中,像运算符一样使用'$'正则表达式来表示任何字符串的结尾..而'%'用于开头..所以任何字符串都属于这个正则表达式,这就是它返回所有记录的原因。 Please refer to http://dev.mysql.com/doc/refman/5.0/en/pattern-matching.html once.
请参阅http://dev.mysql.com/doc/refman/5.0/en/pattern-matching.html一次。 Hope, this will help you.
希望这个能对您有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.