开发者

Trouble with LIKE MySQL query

I have the following MySQL query that I execute from a .php page

SELECT * FROM servers WHERE name LIKE '%$value%'

which, when executed, selects 0 rows (However, the query runs successfully, so I can't use mysql_error() to debug). When I run the query in PHPMyAdmin it selects 开发者_Python百科the appropriate rows. Other queries such as

SELECT * FROM servers

work fine. I can put my code up here if it will help.


Edit: Here's something offering an improvement based on Marek's answer below. Please see the comments regarding the practice of putting variables directly into queries and consider using prepared statements. Anyway, here it goes.

  1. PHP substitutes variables inside doubly-quoted strings, but not inside singly-quoted strings.
  2. One quote character is just treated as an ordinary character within a string delimited by the other.

Putting that together, you can write:

$q = "SELECT * FROM servers WHERE name LIKE '%$value%'"; //Fine

You cannot write:

$p = 'SELECT * FROM servers WHERE name LIKE "%$value%"'; //Broken!

$q works because it's a doubly-quoted string, and the apostrophes are just ordinary characters. $p does not work because it's a singly-quoted string.

As pointed out by GoodFather below, you can also say ${value} to avoid ambiguities with the ambient string, e.g. $r = "ABC${value}DEF";.


You really need to look at doing this query more safely. This will help with your issue as well. As it stands, you are vulnerable to SQL injection. Look at the examples from the PHP manual for how to do it right:

http://php.net/manual/en/function.mysql-query.php

EDIT: From your comments you mentioned that you are already taking care of the string properly, which is great. The code below should fix your problem.

For example, you could rewrite your query statement (in PHP) like so:

$query = sprintf("SELECT * FROM servers WHERE name LIKE '%". mysql_real_escape_string($value) . "%'");

That will clean up your code and it will also handle the issue with your LIKE statement not working properly.

Here is another good article on the subject:

http://joshhighland.com/blog/2008/07/06/php-sprintf-sql-like/


Are you expecting a case-sensitive or case-insensitive query? I'm betting case-insensitive since you're expecting results but not seeing them. Take a look at your database's default collation or the table's specific collation and make sure it ends in _ci, whatever it is.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜