我试图编码搜索引擎。
如果我输入像西海岸这样的查询,它的工作区别于此,我也得到了东海岸的结果。发生这种情况是因为东西方的关键词包含海岸作为单个词。
但是我想用这行代码分开两个代码:
<?php
$k = $_GET['k'];
$terms = explode(" ", $k);
$query = "SELECT * FROM Search WHERE ";
foreach ($terms as $each){
$i++;
if($i == 1)
$query .= "keywords LIKE '%$each%' ";
else
$query .= "OR keywords LIKE '%$each%' ";
}
如果我回答说在搜索表单中使用的关键字确实是分开的,但是进一步他们没有 我该如何解决这个问题?
<?php
$k = $_GET['k'];
$terms = explode(" ", $k);
$query = "SELECT * FROM Search WHERE ";
foreach ($terms as $each){
$i++;
if($i == 1)
$query .= "keywords LIKE '%$each%' ";
else
$query .= "OR keywords LIKE '%$each%' ";
}
if($k == "" || $k == " ")
{
echo "<p> Please enter a valid search term."; //If search is empty or contains only a space.
exit;
}
//connect to database
mysql_connect("LOCALHOST" ,"ROOT" ,"PASSWORD");
mysql_select_db("DATABASE");
$query = mysql_query($query);
$numrows = mysql_num_rows($query);
if($numrows > 0){
while($row = mysql_fetch_assoc($query))
{
$id = $row['id'];
$title = $row['title'];
$description = $row['description'];
$keywords = $row['keywords'];
$link = $row['link'];
echo "<h2><a href ='$link' class='searchcolor' color='#a8a8a8'> $title</a></h2>
$description<br />
This page contains information about \"<b>$query</b>\"<br /><hr>";
}
}
else
echo "No results for \"<b>$k</b>\"";
//disconnect
mysql_close();
?>
答案 0 :(得分:0)
您的查询:
SELECT * FROM Search WHERE keywords LIKE '%west%' OR keywords LIKE '%$coast%';
由于OR
,将返回与 匹配的结果。如果您希望结果与所有关键字匹配,请使用AND
。
即。变化
$query .= "OR keywords LIKE '%$each%' ";
要
$query .= "AND keywords LIKE '%$each%' ";