我正在为图书馆系统做一个整理,并修复杂乱的书名。 我想编写一个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
任何有关如何执行此操作的帮助或想法将不胜感激。提前谢谢。
答案 0 :(得分:0)
在SQL where 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
答案 1 :(得分: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%”将导致其键以&和
开头“%HERE”将导致其键结束,
但如果你输入“%HERE%”,它将导致所有包含“key_element”的元素作为子字符串。 谢谢
答案 2 :(得分:0)
PHP stristr用于查找数组中的每个关键字,而不是SQL。
search in text , and select keywords by 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 . "'";
...
}
}
它不整洁,必须有更好的方法,但......至少它有效! 再次感谢那些试图帮助我的人:)