Reputation: 133
I've a situation where my wildcard search is not really working how I thought it should... This is the MySQL query I am running and it will return only whole words...
eg. If I enter "phone" as a search word it will return all rows with "phone" in it but not rows with "phones" (note the added 's')
mysql_query(" SELECT * FROM posts WHERE permalink = '$permalink' AND LOWER(raw_text) LIKE '%$str%' " );
How can I get it to return all variations of the search word? Obviously I know this could run into problems as it could return all sorts of matches if the user enters a common run of letters, I thought I could make this part of the advanced search option.
ADENDUM I have narrowed it down to not a problem with the wildcard but with what I'm doing with the returned data... It is in my Regex that I am throwing at the data.
$pattern= "/(?:[\w\"',.-]+\s*){0,5}[\"',.-]?\S*".$str."(\s|[,.!?])(\s*[A-Za-z0-9.,-]+){0,5}/";
preg_match_all($pattern, $row["raw_text"], $matches);
The regex is not finding the string in the raw data that I am returning so it is throwing me a null. A new problem, I'm not that familiar with regex so I will havbe to fugure this one out as well... Maybe I'll be throwing up a new question soon!
Thanks, M
Upvotes: 0
Views: 2760
Reputation: 70065
I think something else is going on. The %
part of the query seems correct. And this seems to be confirmation:
select 'phones' LIKE '%phone%';
+-------------------------+
| 'phones' LIKE '%phone%' |
+-------------------------+
| 1 |
+-------------------------+
1 row in set (0.00 sec)
By the way, I really hope you are doing a rigorous sanitation on $str
(and $permalink
too if it is from user input). You should only allow alphanumerics and a small number of other safe characters (spaces, probably) and you should be running it through mysql_real_escape_string()
before using it in mysql_query()
. Better yet, have a look at PDO
.
Anyway, back to troubleshooting this: One thing to try might be to have the program log the string your sending to mysql_query()
. Basically, change the call to mysql_query() to a call to error_log()
or echo()
or something like that. Then copy and paste the resulting query into MySQL command-line tool or PHPmyAdmin or whatever. When that query doesn't work the way you expect, at least you can look at it and tweak it to figure out what's up. And who knows, maybe it will be super obvious once you see the query spelled out.
Upvotes: 1
Reputation: 424983
I suspect you have a trailing space in your $str
variable, which would explain what you're seeing: Your LIKE
criterion would be '%phone %'
, which matches "... phone ..."
, but not "... phones ..."
.
Try trimming your value first.
Upvotes: 0