PHP SQL SELECT where like search item with multiple words(PHP SQL SELECT where like search item with multiple words)
问题描述
我有一个查询表单的 select where like 查询,如下所示:
I have a select where like query for a seach form which is as follows:
<?php
$bucketsearch = sanitizeone($_POST["bucketsearch"], "plain");
$bucketsearch = strip_word_html($bucketsearch);
?>
if(isset($_POST['search'])){
$result=MYSQL_QUERY( "SELECT * FROM buckets where bucketname like '%$bucketsearch%' order by bucketname");
}else{
$result=MYSQL_QUERY( "SELECT * FROM buckets order by bucketname");
}
我的问题是,如果有人搜索例如apple and pear",我没有得到任何包含任何单词的结果,我只能让它返回包含所有单词的结果(1 个结果).
My problem is that if someone searches for instance for "apple and pear" i do not get any results that contain any of the words, i can only make it return results (well 1 result) with all the words in it.
谁能帮我让这个搜索更通用一些??提前致谢.
Can anyone help me make this search a bit more versitle?? Thanks in advance.
推荐答案
所以您想要使用输入的每个词进行 AND 搜索,而不是使用确切的字符串?这样的事情怎么样:
So you want an AND search using each of the words entered, rather than the exact string? Howabout something like this:
$searchTerms = explode(' ', $bucketsearch);
$searchTermBits = array();
foreach ($searchTerms as $term) {
$term = trim($term);
if (!empty($term)) {
$searchTermBits[] = "bucketname LIKE '%$term%'";
}
}
...
$result = mysql_query("SELECT * FROM buckets WHERE ".implode(' AND ', $searchTermBits).");
这会给你一个查询:
SELECT * FROM buckets WHERE bucketname LIKE '%apple%' AND bucketname LIKE '%and%' AND bucketname LIKE '%pear%'
如果您想匹配任何搜索词而不是全部,请将 AND 更改为 OR.进一步的改进可能涉及定义一些停用词,例如和",以提供更好的结果.
change the AND to an OR if you want to match any of the search terms rather than all. Further improvements could involve defining some stop words like 'and' to give better results.
这篇关于PHP SQL SELECT where like search item with multiple words的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:PHP SQL SELECT where like search item with multiple words
基础教程推荐
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01
- 使用 PDO 转义列名 2021-01-01
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01
- PHP 守护进程/worker 环境 2022-01-01
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01
- 如何在 XAMPP 上启用 mysqli? 2021-01-01
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01
- HTTP 与 FTP 上传 2021-01-01
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01