multiple search value in php and mysql

纵然是瞬间 提交于 2019-12-08 03:10:11

问题


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.


回答1:


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



回答2:


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




回答3:


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



回答4:


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


来源:https://stackoverflow.com/questions/15289618/multiple-search-value-in-php-and-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!