Php 与MySQL中的数据匹配的搜索关键字
我正在为图书馆系统做一个整理,并修复混乱的书名。 我想编写一个SQL查询或PHP代码来搜索与MySQL表中的数据匹配的关键字 [tbl_关键字]Php 与MySQL中的数据匹配的搜索关键字,php,mysql,search,Php,Mysql,Search,我正在为图书馆系统做一个整理,并修复混乱的书名。 我想编写一个SQL查询或PHP代码来搜索与MySQL表中的数据匹配的关键字 [tbl_关键字] id | keyword | title ==================================================================== 1 | Harry Potter | Harry Potter 2 | Philosopher's Stone | [Harry P
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
任何关于如何做到这一点的帮助或想法都将不胜感激。提前感谢。在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
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_元素放在两个“%HERE%”之间,因为
“此处%”将显示其键以和开头的结果
“%HERE”将显示其键以结尾的结果
但是如果您将“%HERE%”放在这里,它将生成所有包含“key\u element”作为子字符串的元素。
感谢您使用PHP stristr而不是SQL来查找数组中的每个关键字 然后,在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 . "'";
...
}
}
它不整洁,肯定有更好的方法,但是。。至少它起作用了!
再次感谢那些试图帮助我的人:)看看这个谢谢,但我想做的是相反的方向,在$element\u to\u search中搜索表中的关键字$element_to_search=“[Harry Potter]哈利·波特与魔法石(1)”;谢谢,但我想检查$input\u search表中是否有关键字。