PHP mysql多关键字搜索


PHP MySqli Multiple Keyword Search

我在我的网站中使用ajax搜索。用户可以搜索房屋。我想让用户做一个精确的搜索与他想要的关键字。但我的问题是,我不知道用户输入了什么,我可以搜索多少个关键字。这是我的查询:

$query = "Select a.*,c.name as agent_name,d.country_name,e.state_name,g.city from #__osrs_properties as a"
                                ." inner join #__osrs_agents as c on c.id = a.agent_id"
                                ." inner join #__osrs_types as f on f.id = a.pro_type"
                                ." inner join #__osrs_categories as j on j.id = a.category_id"
                                ." inner join #__osrs_countries as d on d.id = a.country"
                                ." inner join #__osrs_states as e on e.id = a.state"
                                ." inner join #__osrs_cities as g on g.id = a.city"
                                ." where a.approved = '1' and a.published = '1' and a.category_id = '$category->id' and (";
                        //
                        $newKeyword = explode(" ",$keyword);    
                        $query1="j.category_name like '%$newKeyword[0]%' and f.type_name like '%$newKeyword[1]%' and  g.city like '%$newKeyword[2]%'";

它工作,但当用户只输入3个关键字,而不是更多。

使用OR代替AND

$query1 = "j.category_name like '%$newKeyword[0]%' OR f.type_name like '%$newKeyword[1]%' OR g.city like '%$newKeyword[2]%'";

希望对你有帮助。

您需要知道用户提供的是什么。例如,您想要匹配的字段。现在,您假设关键字是按一定顺序排列的,但这能保证吗?如果你不能确定用户是否会提供所有3个,我怀疑没有。

我建议将关键字分解为可以确定的字段,并将它们单独应用于查询。否则将无法知道三个关键字中哪个是提供的。

您还需要对用户提供的值进行消毒,以防止恶意注入。

要获得准确的结果,您应该在查询

中使用正则表达式

query1美元= " j。category_name REGEXP '$newKeyword[0]'和f.type_name REGEXP '$newKeyword[1]'和g.city REGEXP '$newKeyword[2]'";

最好的选择是不要尝试重新发明轮子,只是在MySQL中使用FULLTEXT索引。然后,只需在所有关键字前加上+(加号),并通过正常的SELECT进行搜索。MySQL将照顾你的关键字组合,无论顺序和无论字段大小在你的数据库