mysql multiple keyword search in any order [duplicate]

给你一囗甜甜゛ 提交于 2020-01-26 04:38:25

问题


I have a simple MySQL database keyword search that is functional. However results for the search are not being returned if the keywords are not in the same order as entered in the database. For example searching for "dog cat lion" will return a result, but searching for "dog lion cat" will return no results. Any help on how to fix this issue would be greatly appreciated. Here is my code.

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Part Search</title>
</head>

<body>
<?php
$username = "xxxx";
$password = "xxxx";
$hostname = "localhost"; 

//connection to the database
mysql_connect($hostname, $username, $password); 
mysql_select_db("wesco");

$search = mysql_real_escape_string(trim($_POST['searchterm']));

$find_parts = mysql_query("SELECT * FROM `parts` WHERE `keywords` LIKE '%$search%'");

while($row = mysql_fetch_assoc($find_parts))
{
$name = $row['name'];
echo "$name<br />";

}

?>
</body>
</html>

回答1:


You could use something like this

$searchArray = explode(" ", $_POST['searchterm']);
$query = "";
foreach($searchArray as $val) {
    $search = mysql_real_escape_string(trim($val));
    if (!empty($query)) {
        $query = $query . " OR "; // or AND, depends on what you want
    }

    $query = $query . "`keywords` LIKE '%$search%'";
}

if (!empty($query)) {
    $find_parts = mysql_query("SELECT * FROM `parts` WHERE $query");
}

Also, you should stop using the mysql_* functions and start using the object oriented implementation of mysqli.




回答2:


You need to order your Query. if you have an auto_incremented Id you could go:

$find_parts = mysql_query("SELECT * FROM `parts` WHERE `keywords` LIKE '%$search%' ORDER BY row_id asc");

you can order by Name or really anything:

$find_parts = mysql_query("SELECT * FROM `parts` WHERE `keywords` LIKE '%$search%' ORDER BY name asc");



回答3:


Two options:

  1. use the build in mysql search functionality.

https://dev.mysql.com/doc/refman/5.6/en/innodb-fulltext-index.html

this is probably the better solution.

  1. if you want to continue to use LIKE, then split the words as follows.

    select * from parts where ( keywords LIKE '%$word1%' AND keywords LIKE '%$word2%' AND keywords LIKE '%$word3%' )



来源:https://stackoverflow.com/questions/35230164/mysql-multiple-keyword-search-in-any-order

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