multiple search value in php and mysql

半城伤御伤魂 提交于 2019-12-06 21:58:30

There's a decent article here which will give you a decent introduction to searching MySQL with PHP, but basically what you want to do is split your search phrase in to parts and then use them in the MySQL query. For instance:

<?php
  $search = 'Gold Chain Shirt';
  $bits = explode(' ', $search);

  $sql = "SELECT name FROM product WHERE name LIKE '%" . implode("%' OR name LIKE '%", $bits) . "%'";

The above will generate this query:

SELECT name FROM product WHERE name LIKE '%Gold%' OR name LIKE '%Chain%' OR name LIKE '%Shirt%'

You really need to look at FULLTEXT indexing, then read about FULLTEXT Query Expressions.

If I understood you correctly, you want to search all items that have value "Gold Chain" or "Shirt". In this case, as you tag the question as "php", you could do this by changing the $search as the whole WHERE clause. I do this such way (example with showing different conditions to explain the idea):

$search_array=array('name LIKE "%Gold Chain%"', 'price > 5');
$where=implode($search_array,' OR '); // you might wish ' AND '

some_function_to_query('SELECT name FROM product WHERE '.$where);

You could improve your search by doing : '%$search' to search only from the beginning of the String to get more results.

Than, if you wanted to search each word from a sentence, you could do like that :

$search = 'Gold Chain Shirt';
$searches = explode(' ', $search);
$query = "SELECT * FROM product WHERE name ";
foreach($searches as $word) {
    $query .= "LIKE '%{$word}' OR ";
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!