0

我正在整理图书馆系统并修复凌乱的书名。我想编写一个 SQL 查询或 PHP 代码来搜索与 MySQL 表中的数据匹配的关键字。

[tbl_keywords]

id | keyword             | title
====================================================================
 1 | Harry Potter        | Harry Potter
 2 | Philosopher's Stone | [Harry Potter] Harry Potter and the Philosopher's Stone
 3 | Chamber of Secrets  | [Harry Potter] Harry Potter and the Chamber of Secrets
 4 | Dr. Seuss           | Dr. Seuss
 5 | Green Eggs and Ham  | [Dr. Seuss] Green Eggs and Ham
 6 | The Cat in the Hat  | [Dr. Seuss] The Cat in the Hat

例如,

"Harry Potter(1)" => matches 1
"[Harry Potter] Harry Potter and the Philosopher's Stone(1)" => matches 1 and 2
"(HARRY POTTER2) THE CHAMBER OF SECRETS" => matches 1 and 3
"Dr. Seuss - Green Back Book" => matches 4
"Green eggs and ham" => matches 5
"the cat in the hat(Dr. Seuss)" => matches 4 and 6

这也可能(易于实施)吗?如果要做的太多,我只需将变量值添加到表中..

"HarryPotter" => matches 1
"Dr.Seuss" => matches 4
"Dr Seuss" => matches 4

任何有关如何执行此操作的帮助或想法将不胜感激。提前致谢。

4

3 回答 3

0

Jst是这样写的

$element_to_search='//get here the input to search';
$sql2 = 'Select * from `tbl_keywords` where keyword LIKE "%'.$element_to_search.'%" OR title LIKE "%'.$element_to_search.'%"';

在您的情况下,始终将要搜索的 key_element 放在两个“%HERE%”之间,因为

"HERE%" 将产生键以 and 开头的结果

"%HERE" 将得到其键以结尾的结果,

但是如果你输入“%HERE%”,它将导致所有包含“key_element”作为子字符串的元素。谢谢

于 2012-09-05T07:51:01.263 回答
0

在 SQL where 条件中使用 LIKE。

例子:

$input_search //your search input
$sql1 = 'Select * from `tbl_keywords` where keyword ="'.$input_search.'"';
//...the rest of code
$sql2 = 'Select * from `tbl_keywords` where keyword LIKE "%'.$input_search.'%" OR title LIKE "%'.$input_search.'%"';
//... the rest of code
//here is IF condition to get the desire result from the sql result you got
于 2012-09-05T06:10:47.653 回答
0

PHP stristr 用于查找数组中的每个关键字,而不是 SQL。

在文本中搜索,并通过 php 选择关键字

然后,在 MySQL 表中查找 ID 以获取其他信息/字段;标题、类别等

$keywords = array(NULL, 'Harry Potter', 'Philosopher\'s Stone', 'Chamber of Secrets');
$input_title = "[Harry Potter] Harry Potter and the Philosopher\'s Stone(1)"

$keyword_found = array();
foreach ($keywords as $key => $val) {
    if (stristr($input_title, $val)) $keyword_found[] = $key;
}

if ($keyword_found) {
    foreach ($keyword_found as $val) {
        $sql = "SELECT * FROM `tbl_keywords` WHERE `id` = '" . $val . "'";
        ...
    }
}

它不整洁,必须有更好的方法,但是..至少它有效!再次感谢那些试图帮助我的人:)

于 2012-09-05T11:52:56.470 回答