我创建了搜索引擎,所以当有人在搜索框中键入时,它会从我的数据库中获取数据,并以图像显示结果。
一切都很好,但如果我在数据库中有名称为"兰博基尼"的数据,当有人在搜索框中键入"lambo"或"Lamborghini"时,它会很好地工作并显示结果,但当他键入"Lamborgchini car"时,不会显示任何结果。
这是我的PHP代码:
<html>
<link href="css/imgpages.css" rel="stylesheet" type="text/css">
<head>
<title>Search the Database</title>
</head>
<body>
<form action="" method="post">
Search: <input type="text" name="term" /><br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
<?php
include("connection.php");
$term = $_POST['term'];
$query = mysql_query("select * from save_data where Title like '%$term%'");
while($row = mysql_fetch_array($query)) {
$post_id = $row['ID'];
$title = $row['Title'];
$image = $row['Name'];
?>
<div id="body">
<a href="pictures.php?title=<?php echo $title; ?>">
<div id="title"><?php echo $title; ?></div></a>
<a href="pictures.php?title=<?php echo $title; ?>">
<img src='uploads/<?php echo $image; ?>' width='140' height='140'></a>
</div>
<?php } ?>
您应该:
- 修复您的SQL(使其安全-如果您保持这种状态,只需一次搜索就可以删除整个数据库,切换到mysqli或PDO,因为mysql_*函数已被弃用)
- 将查询字符串拆分为单独的单词,并决定如何处理它们(是使用OR还是and…换句话说,是否所有搜索词都需要匹配,或者其中任何一个,等等)
当您处理完所有这些并决定使其更高级时,您应该了解全文搜索。
这是因为{%$term%}意味着查询尝试搜索包含$term中所有字符串的内容。试试这个:
$term = explode(" ",$term);
if (count($term) > 0) {
$Where = '';
foreach($term as $Item) {
$Where .= "Title like '%$Item%' OR ";
}
$Where = substr($Where,0,-4);
$query = mysql_query("SELECT * FROM `save_data` WHERE $Where");
}
通过这种方式,搜索将检查出所有单词。
正如上面的人所说,只需将输入字符串分解成一个数组,并搜索大多数元素匹配的文档(描述、关键字)。还要注意SQL注入。
首先让你的词条搜索爆炸,这样它就会进入一个数组
<?php
$term = $_POST['term'];
$words = explode(" ", $term);
?>
然后为搜索的mysql_query创建一个forearch循环,并使用"OR"内爆
<?php
foreach ($words as $words)
{
$queries[]="select * from save_data where Title LIKE '%" .
mysql_real_escape_string($words) . "%'";
}
$query=implode(' OR ' ,$queries);
$results=mysql_query($query);
while($row = mysql_fetch_array($results))
{
$post_id = $row['ID'];
$title = $row['Title'];
$image = $row['Name'];
?>
<div id="body">
<a href="pictures.php?title=<?php echo $title; ?>">
<div id="title"><?php echo $title; ?></div>
</a>
<a href="pictures.php?title=<?php echo $title; ?>">
<img src='uploads/<?php echo $image; ?>' width='140' height='140'>
</a>
</div>
<?php } ?>