0
我做了一个搜索功能,并得到它的工作,但我有1个问题: 如果我输入1个单词(可以说“测试”)它工作正常,发现包含“测试” 。但是如果我输入“测试别的东西”,它可以找到任何东西。MySQL搜索脚本不能按预期工作
如何让脚本搜索$ _POST ['search']中的每个单词?
这里是我的代码:
$itemOutput = '';
$dbhandle = mysql_connect('host', 'name', 'pass') or die("Unable to connect to MySQL");
$selected = mysql_select_db('my_website_db', $dbhandle) or die("Could not select database");
$search_term = mysql_real_escape_string($_POST['search']);
if (!isset($search_term) || $search_term == '' || $search_term == ' ' || !ctype_alpha($search_term)) { $result_count = "0"; } else {
$fetch_items = mysql_query("SELECT * FROM products WHERE name LIKE '%{$search_term}%' OR short_info LIKE '%{$search_term}%'");
while($shop_items = mysql_fetch_array($fetch_items)) {
$item_id = $shop_items['id'];
$item_name = $shop_items['name'];
$item_price = $shop_items['price'];
$item_image = $shop_items['image']; }
$itemOutput .= '<div class="item-box"> <img src="'.$item_image.'" class="item-image" />';
$itemOutput .= '<div class="item-price"> <a style="padding-left: 15px; font-size: 14px; padding-top: 3px;">Kun </a> <a><b>'.$item_price.' kr.</b></a> </div> <br>';
$itemOutput .= '<div class="item-name"> <a>'.$item_name.'</a> </div> <br>';
$itemOutput .= '<a href="vare.php?id='.$item_id.'"><button class="item-button">Køb her ></button></a> </div>';
}
编辑:感谢所有的投入,我得到它的工作:)
请[停止使用'mysql_ *'函数](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php)。他们不再被维护,并[正式弃用](https://wiki.php.net/rfc/mysql_deprecation)。了解[准备的陈述](http://en.wikipedia.org/wiki/Prepared_statement),并考虑使用PDO,[它不像你想象的那么难](http://jayblanchard.net/demystifying_php_pdo.html) 。 –
将这些术语拆分并将每个单词附加到它自己的“like”分组中。例如'$ query。='(name LIKE'%{$ search_term}%'或short_info LIKE'%{$ search_term}%')或'; //去掉最后一个“或”以避免转义或更好地使用支持预处理语句的驱动程序。 – chris85
每个单词或每个单词的顺序?如果按照这个顺序简单地用@ chris85表示的任何顺序代替空格 – xQbert