an I using LIKE incorrectly?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
someguyhere
Forum Contributor
Posts: 181
Joined: Sun Jul 27, 2008 3:24 pm

an I using LIKE incorrectly?

Post 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.
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: an I using LIKE incorrectly?

Post 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.
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: an I using LIKE incorrectly?

Post 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.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: an I using LIKE incorrectly?

Post 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.
someguyhere
Forum Contributor
Posts: 181
Joined: Sun Jul 27, 2008 3:24 pm

Re: an I using LIKE incorrectly?

Post by someguyhere »

Thanks for the heads up guys!
Post Reply