Searching a mysql field contents, in any order

    I have a php script which basically has a select statement, something along the lines of:

select * FROM TABLE x WHERE Name LIKE '%$variable%'

$variable is a passed variable from an input text field.

This works great IF the text being searched is in that order, so if the name field contains:

John William Smith

and I search for John William - it returns the record, but not if I search for:

John Smith, or Smith William

How can this be achieved?

Many thanks for your help.
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Nathan RileyFounderCommented:
Does the variable always include spaces?

You could explode your variable with PHP by space, then loop them through your query statement.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Ray PaseurCommented:
You can use the MySQL "OR" clause to create the query.  Something like this in the WHERE clause:

WHERE Name LIKE %john% OR Name LIKE %smith%

You will want to experiment with the exact patterns - set up lots of test cases.  "John" will also match "Johnson" and "Smith" will also match "Blacksmith."  You may find that padding the strings with blanks may help.  However "Smith " would not necessarily match "Smith" at the end of the name.  A regular expression might help.

More advanced name matching can be achieved with sound-alike terms using soundex() and metaphone().
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
MySQL Server

From novice to tech pro — start learning today.