Page 1 of 1

an I using LIKE incorrectly?

Posted: Wed Feb 09, 2011 2:00 pm
by someguyhere

Code: Select all

			$query = "SELECT * FROM wp_network_members WHERE company LIKE '$_POST[1]'";
I get no results and there are two rows in the table that *should* show up.

Re: an I using LIKE incorrectly?

Posted: Wed Feb 09, 2011 2:51 pm
by John Cartwright
You need to include wildcards in your search. Plus, you need to escape your input with mysql_real_escape_string() to avoid SQL injection.

Code: Select all

$query = "SELECT * FROM wp_network_members WHERE company LIKE '%". mysql_real_escape_string($_POST[1]) ."%'";
Notice the % wildcards. You can remove the first or second wildcard if you only want to use partial matching.

Re: an I using LIKE incorrectly?

Posted: Wed Feb 09, 2011 2:55 pm
by pickle
DO NOT RUN THIS QUERY!

What would happen if I submitted a form where $_POST[1] was this:
';TRUNCATE `wp_network_members`
The entire table would be deleted. Never, ever put post variables directly into a query. You should always escape them first with mysql_real_escape_string().

To answer your question, you're not using LIKE wrong, but probably not in the way you want.

I'm assuming $_POST[1] is intended to be a word, and you want to find all members that have that given word in their company name. If this is the case, you'd want to add % before and after, like so:
MySQL wrote:SELECT * FROM wp_network_members WHERE company LIKE '%$cleaned_posted_content%'
. The '%' is a wildcard, much like '*' in regular expressions.

Re: an I using LIKE incorrectly?

Posted: Wed Feb 09, 2011 3:00 pm
by John Cartwright
pickle wrote:DO NOT RUN THIS QUERY!

What would happen if I submitted a form where $_POST[1] was this:
';TRUNCATE `wp_network_members`
Only the first query prior to ; would be executed, since mysql_query() is only capable of running a single query. But that doesn't mean they won't be able to malicious things to your query ;)

It's that or a syntax error, I can't remember.

Re: an I using LIKE incorrectly?

Posted: Wed Feb 09, 2011 3:23 pm
by someguyhere
Thanks for the heads up guys!