在搜索脚本中添加多个搜索查询?

时间:2013-02-03 12:48:14

标签: php mysql

我正在试图找出一种允许用户通过多个查询进行搜索的方法,目前搜索脚本我只允许一个类似匹配的单词,就像数据库中的那样。

所以,如果我输入女性,我会得到所有女性用户,但我想要做的是允许用户输入棕色头发的女性。

因为'头发'不是一个查询而且没有存储在数据库中,但仍然允许搜索调出查询='brown'和query ='women'。

我尝试简单地将OR替换为'%'。查询。“%'与AND但这意味着如果用户只搜索女性,则不会显示任何内容,因为它要求包含所有查询。

任何人都可以告诉我如何做到这一点我真的很挣扎吗?

感谢。

              
<?php
//PHP CODE STARTS HERE

if(isset($_GET['submit'])){

// Change the fields below as per the requirements
$db_host="localhost";
$db_username="root";
$db_password="";
$db_name="";
$db_tb_atr_name="display_name";

//Now we are going to write a script that will do search task
// leave the below fields as it is except while loop, which will display results on screen

mysql_connect("$db_host","$db_username","$db_password");
mysql_select_db("$db_name");

$query=mysql_real_escape_string($_GET['query']);


$query_for_result=mysql_query("SELECT * 
                        FROM ptb_stats
                        WHERE display_name like '%".$query."%' OR location LIKE '%".$query."%' OR sex LIKE '%".$query."%' OR nationality LIKE '%".$query."%' OR ethnicity LIKE '%".$query."%' OR age LIKE '%".$query."%' OR local_station LIKE '%".$query."%' OR height LIKE '%".$query."%' OR weight LIKE '%".$query."%' OR status LIKE '%".$query."%' OR build LIKE '%".$query."%' LIMIT 5");
echo "<div class=\"search-results\">";
while($data_fetch=mysql_fetch_array($query_for_result))

{

    echo "<div class=\"text\"><a href=\"profile.php?id={$data_fetch['user_id']}\" class=\"search\">";
    echo "<div class=\"spacing\"><img width=35px height= 30px src=\"data/photos/{$data_fetch['user_id']}/_default.jpg\" class=\"boxgridsearch\"/> "; 
     echo substr($data_fetch[$db_tb_atr_name], 0,160);
    echo "</a></div></div>";

}
echo "<div class=\"morebutton-search\"><a href=\"search_results.php?query=$query\">+ view more results</a></div>";



mysql_close();
}

?>

1 个答案:

答案 0 :(得分:0)

使用全文搜索

mysql_query("SELECT *,MATCH(display_name, location, sex, nationality, ethnicity, age, local_station, height, weight, status, build) AGAINST ('$query' IN BOOLEAN MODE) AS relevance FROM ptb_stats WHERE MATCH(display_name, location, sex, nationality, ethnicity, age, local_station, height, weight, status, build) AGAINST('$query' IN BOOLEAN MODE) ORDER BY relevance DESC LIMIT 5");

下面

('$query' IN BOOLEAN MODE) AS relevance

表示您按相关性顺序获得结果,但如果您希望以任何其他mysql方式(如random())进行排序,则可以使用:

mysql_query("SELECT * FROM ptb_stats WHERE MATCH(display_name, location, sex, nationality, ethnicity, age, local_station, height, weight, status, build) AGAINST('$query' IN BOOLEAN MODE) order by random() DESC LIMIT 5");