MySqli查询与PHP数组中的任何值一样

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?

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);

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)."%'";