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:
$terms = explode(' ', $search_term);
LIKE
foreach ($terms as $term) { $term = mysql_real_escape_string($term); $likes[] = "field LIKE '%$term%'"; }
$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)."%'";