简体   繁体   中英

multiple search value in php and mysql

I'm trying to create a search engine in php and mysql. The search engine should be able to accept multiple value and display all possible result, i checked this thread php/mysql search for multiple values , but i need to use global variable at the place where LIKE '$search%' is. This is how my sql statement looks like,

SELECT name FROM product WHERE name LIKE '%$search%

the variable search is declared correctly,now everything works fine when i search specifically, such as Gold chain will show Gold chain.But when i search another name together such Gold Chain Shirt,where shirt is another product's name,the result is not showing. How should i change my sql command to get multiple result from multiple value searched? I'm very sorry i did not tell earlier that i was asked to do it in 3 tier programming.

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%'

您确实需要查看FULLTEXT索引,然后阅读有关FULLTEXT查询表达式的信息

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 ";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM