使用PHP搜索数据库
当用户在数据库中搜索某个名称时,我试图用红色突出显示找到的单词,代码如下:使用PHP搜索数据库,php,Php,当用户在数据库中搜索某个名称时,我试图用红色突出显示找到的单词,代码如下: echo "<table class='nameList'>"; echo "<tr><h3>You have searched for <span class='red'>$query</span> ...Please find the details.</h3></tr>"; echo "<tr> <th >U
echo "<table class='nameList'>";
echo "<tr><h3>You have searched for <span class='red'>$query</span> ...Please find the details.</h3></tr>";
echo "<tr> <th >UN Number</th> <th>Full Name</th></tr>";
$result = mysql_query("SELECT UN,NAME FROM mytable WHERE (`NAME` LIKE '%".$query."%')") or die(mysql_error());
if(mysql_num_rows($result) > 0){
while($results = mysql_fetch_array($result)){
echo "<tr><td>".$results['UN']."</td> <td>".$results['NAME']."</td></tr>";
}
}else{
echo "<tr><td colspan='2'>Sorry..No results for <span class='red'>$query</span>, try again!</td><tr>";
echo "</table>";
echo”“;
echo“您已搜索$query…请查找详细信息。”;
呼应“联合国编号全名”;
$result=mysql\u query(“从mytable WHERE(`NAME`类似“%”,$query.%')中选择UN,NAME”)或die(mysql\u error());
如果(mysql_num_rows($result)>0){
而($results=mysql\u fetch\u数组($result)){
回显“$results['UN']”.$results['NAME']”;
}
}否则{
echo“对不起,$query没有结果,请重试!”;
回声“;
在使用echo
当结果来自数据库时,您需要在结果中找到您的查询,并将其替换为具有红色样式或所需样式的范围。在示例中,我使用了background color=yellow;
您可以将其更改为color=red;
// Create a function that highlight a list of words in a string.
function highlightWords($string, $words)
{
// foreach keyword as a word
foreach ( $words as $word )
{
// find the word and replace it with background color = yellow , change it to red if you want.
$string = str_ireplace($word, '<span style="background-color:yellow">'.$word.'</span>', $string);
}
// return the string
return $string;
}
// specify the words you are looking for
$words = array("Zebra");
// your string
$string = "My Name Is Zebra will Zebra do this?";
// highlight it
$string = highlightWords($string, $words);
// echo it
echo $string;
//创建一个函数,突出显示字符串中的单词列表。
函数highlightWords($string,$words)
{
//foreach关键字作为一个词
foreach($words作为$word)
{
//找到单词并用background color=黄色替换,如果需要,将其更改为红色。
$string=str_ireplace($word、.$word.''、$string);
}
//返回字符串
返回$string;
}
//指定要查找的单词
$words=数组(“斑马”);
//你的绳子
$string=“我的名字是Zebra,Zebra会这样做吗?”;
//突出显示它
$string=highlightWords($string,$words);
//附和
echo$字符串;
结果如下:
while($results = mysql_fetch_array($result)){
echo "<tr><td>".$results['UN']."</td> <td>".$results['NAME']."</td></tr>";
}
while($results=mysql\u fetch\u array($result)){
回显“$results['UN']”.$results['NAME']”;
}
在
例如:
echo "<tr><td style='color:red'>".$results['UN']."</td> <td style='color:red'>".$results['NAME']."</td></tr>";
echo“$results['UN']”.$results['NAME']”;
问题是什么?您的代码似乎没有试图以红色显示任何内容。请注意,您的代码易受攻击。@user3568485您得到答案了吗,先生?问题是如何在结果中突出显示一个单词。这就是查询。例如,在页面中搜索单词时。您将获得带有请求单词highli的文档太好了!你能解释更多吗…?当你在文档中使用像一样搜索“斑马”一词时,你会得到正确的结果吗?问题是如何突出显示“斑马”一词在数据库中找到的所有结果中。因此,您可以在您在REDI中搜索的单词中看到结果。我认为它很清楚…在上面的我的回答中…如何将其红色…使用样式颜色红色输入..确定您的答案没有突出显示单词..正在突出显示字符串..确定非常感谢,它工作正常。请将答案标记为已接受..您欢迎光临