我有一个 的搜索引擎,但只有当我搜索一个单词时才会这样做。每当我搜索多个关键字时,我只得到1个结果。
示例:在我的数据库中,我有像' test'并且'你好' ; 每当我进入"测试你好"然后点击"搜索"它显示:
1结果你好(这是带有tag = hello的帖子的标题)。
我的代码(search.php - 我获得搜索结果的页面):
<?php
$button = $_GET ['submit'];
$search = $_GET ['search'];
if(!$button) {
echo "you didn't submit a keyword";
} else {
if(strlen($search)<=1) {
echo "Search term too short";
} else {
echo "You searched for <b>$search</b> <hr size='1'></br>";
mysql_connect("localhost","root","root");
mysql_select_db("myschool");
$search_exploded = explode (" ", $search);
foreach($search_exploded as $search_each) {
$x = NULL;
$construct = NULL;
$x++;
if($x==1) {
$construct .="tag LIKE '%$search_each%'";
} else {
$construct .="OR tag LIKE '%$search_each%'";
}
$construct ="SELECT * FROM posts WHERE $construct";
$run = mysql_query($construct);
$foundnum = mysql_num_rows($run);
if ($foundnum==0) {
echo "Sorry, there are no matching result for <b>$search</b>.";
} else {
echo "$foundnum results found !<p>";
while($runrows = mysql_fetch_assoc($run)) {
$title = $runrows ['title'];
$tag = $runrows ['tag'];
echo "<a href='#'><b>$title</b></a><br>";
}
}
}
}
}
?>
问题可能在$x=++
部分周围,因为我认为引擎没有显示甚至搜索数据库中的所有行,并且没有显示num行计数&gt; 1。
先谢谢你们。
编辑:
您搜索了hello test postare
找到1个结果! 你好 找到1个结果!测试 找到1个结果!
如何让它在一个地方添加结果,而不是每次为不同的关键字找到新结果时都说出来?
答案 0 :(得分:0)
您的代码有几个问题。你在这一行错过了"
:
echo "Sorry, there are no matching result for <b>$search</b>";
最后else
没有if
答案 1 :(得分:0)
您需要在foreach语句之前启动$ x变量,如果要将其用作整数,则不要将其设置为null。
$ construct变量有相同的错误,你必须有三次相同的响应,那是因为你必须在调用mysql select之前关闭foreach语句。
$x = 1;
$construct = NULL;
foreach($search_exploded as $search_each)
{
if($x==1) {
$construct .="tag LIKE '%$search_each%'";
} else {
$construct .="OR tag LIKE '%$search_each%'";
}
$x++;
}
$select ="SELECT * FROM posts WHERE $construct";
...
<?php
$button = $_GET ['submit'];
$search = $_GET ['search'];
if(!$button) {
echo "you didn't submit a keyword";
} else {
if(strlen($search)<=1) {
echo "Search term too short";
} else {
echo "You searched for <b>$search</b> <hr size='1'></br>";
mysql_connect("localhost","root","root");
mysql_select_db("myschool");
$search_exploded = explode (" ", $search);
$x = 1;
$construct = '';
foreach($search_exploded as $search_each) {
if($x==1) {
$construct .="tag LIKE '%$search_each%'";
} else {
$construct .="OR tag LIKE '%$search_each%'";
}
$x++;
}
$select ="SELECT * FROM posts WHERE $construct";
$run = mysql_query($select);
$foundnum = mysql_num_rows($run);
if ($foundnum==0) {
echo "Sorry, there are no matching result for <b>$search</b>.";
} else {
echo "$foundnum results found !<p>";
while($runrows = mysql_fetch_assoc($run)) {
$title = $runrows ['title'];
$tag = $runrows ['tag'];
echo "<a href='#'><b>$title</b></a><br>";
}
}
}
}
?>