如何在表中搜索与记录匹配的特定关键字?

时间:2014-03-20 12:15:06

标签: php mysql sql

我有两个查询可以正常工作。我只想知道,如果用户只键入关键字。我仍然希望它能够使用关键字进行搜索并找到匹配项。

$query = "SELECT * FROM `titles` WHERE `Title` = '$search'";

$query2 = "SELECT * FROM `Authors` WHERE `FirstName` = '$search' OR `LastName` = '$search'";

4 个答案:

答案 0 :(得分:2)

使用MySql的LIKE关键字:

 $query = "SELECT * FROM `titles` WHERE `Title` LIKE '%$search%'";    

 $query2 = "SELECT * FROM `Authors` WHERE `FirstName` LIKE '%$search%'
 OR `LastName` LIKE '%$search%'";

答案 1 :(得分:1)

我建议使用全文搜索引擎,自2005年起可在MyISAM和InnoDB中使用documentation 如果你让用户输入多个单词,它比有限运算符更强大,等等。

查询示例:

SELECT * FROM authors
WHERE MATCH (FirstName,NastName)
AGAINST ('$query' IN NATURAL LANGUAGE MODE);

答案 2 :(得分:0)

使用LIKE

$query = "SELECT * FROM titles WHERE Title LIKE '%$search%'";

答案 3 :(得分:0)

使用Mysql LIKE

这是Like

的语法
SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern;

E:

$query = "SELECT * FROM `titles` WHERE `Title` LIKE '%$search%'";

参考http://www.tutorialspoint.com/mysql/mysql-like-clause.htm