我的搜索脚本有问题。
基本上,如果找到结果,搜索一切正常,但如果DB(MySQL)中没有匹配项,那么我的错误不会显示。 我错过了什么吗? 这是代码:
<?php
$term = $_GET['term'];
$sql = mysql_query("select * from search_e where content like '%$term%'");
while ($row = mysql_fetch_array($sql)){
$data = $row['content'];
$first_pos = strpos($data,$term);
if ($first_pos !== false) {
$output = substr($data,max(0,$first_pos - 100),200 + strlen($term));?>
<div>
<p class="ptitle"><?php echo $row["fn"]; ?></p><hr>
Brief summary of contents:
<hr class="hr">
<p style="padding: 5px;">
<i>"<?php echo $output; ?>" </i>..
</p>
</div><br><br>
<?php
}
else {?>
<div><?php echo "Sorry! No results were found using term: ".$_GET['term']."<br>Try using fewer Keywords"; ?></div>
<?php }?>
<?php
}
//close
mysql_close();
?>
这可能是我做错的简单事情,但我只是想不通。我也知道代码很脏,但它是我的工作方式。
我还希望实现我在浏览网上找到的一个小片段,它突出显示短语中的特定单词。
function highlight($sString, $aWords) {
if (!is_array ($aWords) || empty ($aWords) || !is_string ($sString)) {
return false;
}
$sWords = implode ('|', $aWords);
return preg_replace ('@'b('.$sWords.')'b@si', '<strong style="background-color:yellow">$1</strong>', $sString);
}
这可以进入我的脚本吗?
如果我清楚您要完成的任务,我会这样更改它:
if(mysql_num_rows($sql) > 0) {
while ($row = mysql_fetch_array($sql)) {
...
}
} else {
echo("No Records!");
}
巴方是正确的。 保护您的网站和后端数据库免受恶意用户的侵害。
$term = mysql_real_escape_string($_GET['term']);
编辑
为了完整起见,在回顾您发布的内容后,您没有得到输出的原因是,如果没有找到匹配项,while
循环中的任何内容都不会执行,因此您的if($first_pos !== false)
检查毫无意义,除了作为对匹配记录的一种"健全性检查"。
要使用您发布的函数突出显示字词,请更改:
<i>"<?php echo $output; ?>" </i>
自:
<i>"<?php echo highlight($output, array( $term )); ?>" </i>
你的逻辑有缺陷:
- 检索数据库中包含搜索词的所有行
- 遍历这些行:
2a. 检索行
2b. 使用 PHP 再次搜索该行以获取搜索词
2c. 如果找到内容,则显示内容,如果未找到,则显示错误。对每一行执行此操作
当内容已经被数据库过滤时,为什么PHP要重新搜索内容?同样,由于数据库查询不会返回任何未显示内容的行,因此您将永远不会看到错误消息,因为您的 php 搜索每次都会成功。
流程基本上应该是这样的:
$term = mysql_real_escape_string($_GET['term']);
$sql = "SELECT .... WHERE content LIKE '%$term%'";
$result = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($result) == 0) {
echo "Sorry, no results found"
} else {
while ($row = mysql_fetch_assoc($result)) {
... do your output processing here ...
}
}