在MySQL中搜索多个单词 [英] Search multiple words in MySQL

查看:150
本文介绍了在MySQL中搜索多个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用HTML表单来允许用户在数据库表中查找条目:

I am using a HTML form to allow users to find entries in a database table:

   <form action="controller.php" method="get">
   <input type="text" name="word" id="word">

数据库中的表有一个名为关键字的列,其中包含多个值,因此我使用SELECT查询来选择所有具有与用户在表单中键入的内容相匹配的关键字的行.因此controller.php包含以下查询:

The table in my database has a column called keywords that contains multiple values, and so I use a SELECT query to select all rows that have any keywords that match what the user typed into the form. So controller.php contains this query:

$word= $_GET['word'];

$query = SELECT * FROM table WHERE table.keywords LIKE '%{$word}%

这很好用,除非用户在搜索框中输入多个单词.我该如何进行更改,以便当用户在搜索框中输入一个以上的单词时,它将返回其关键字列中具有 个用户单词的所有行.

This works fine, except if a user types more than one word into the search box. How do I alter this such that, when a user types more then one word into the search box, it will return all rows that have either of the users words in its keywords column.

,即用户搜索"apples oranges",并且查询返回在其关键字字段中具有 "apples"或"oranges"的所有行.

i.e, user searches "apples oranges", and the query returns all rows that have either "apples" or "oranges" in their keywords field.

推荐答案

您可以尝试--

$words = explode(' ', $word);
$query = "SELECT * FROM table WHERE table.keywords IN (".implode(',', $words).")";

或-

$query = "SELECT * FROM table WHERE";
$conds = array();
foreach ($words as $val) {
    $conds[] = "table.keywords LIKE '%".$val."%'";
}
$query .= implode(' OR ', $conds);

可以根据需要添加支票.

The checks can be added if required.

这篇关于在MySQL中搜索多个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆