0

I have a PHP array containing values and I want to query the database to find any results where the ItemName contains any of the values in the array.

$current_item = 'Big Fancy Red Car';

$words = explode(' ',$current_item); // Array of words to search

And the query:

SELECT ID FROM store_accessories WHERE ItemName LIKE '%$words%'

How do I select the ID of any items in the table whose ItemName contains any of the values in the $words array?

2
  • What is the table engine of store_accessories? If possible, a FULLTEXT index is an ideal solution, available in MyISAM tables before MySQL 5.6, and InnoDB after. Commented Aug 9, 2015 at 22:30
  • See also these answers which build up a long string of column LIKE %$word% OR... conditions. Considerably less efficient than a FULLTEXT index. Commented Aug 9, 2015 at 22:33

2 Answers 2

1

You can do it like this:

  1. First explode the value into an array:

$terms = explode(' ', $search_term);

  1. Loop the array to add the LIKE

foreach ($terms as $term) { $term = mysql_real_escape_string($term); $likes[] = "field LIKE '%$term%'"; }

  1. Add to the query:

$sql = "select * from table where"; $sql .= implode(' OR ', $likes);

Sign up to request clarification or add additional context in comments.

Comments

0

You can get the LIKE like this directly, also substituting ' with '' and escaping _ and %:

$field = "ItemName";
$like = "$field LIKE '%".str_replace(
   array("'" , "_"  , "%"  , " "                   ),
   array("''", "\\_", "\\%", "%' OR $field LIKE '%"),
   $currentItem)."%'";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.