繁体   English   中英

搜索结果中的粗体搜索词

[英]Bold search term in search results

当用户搜索我的数据库时,我希望搜索词在结果中使用粗体。 我似乎找不到可以轻松在现有代码中实现的教程或解释。 我是PHP新手,所以请耐心等待。 所以,我想要的是如果有人搜索“蓝色”,那么结果将显示类似以下内容:

搜寻字词:
蓝色

结果:
1- 蓝色 -马-黑体色-红眼睛
2-吉米-马- 颜色-黑眼圈

等等等等。

这是我的search.php页面代码:

<?php
$query = $_GET['query']; 
// gets value sent over search form

$min_length = 3;
// you can set minimum length of the query if you want

if(strlen($query) >= $min_length){ // if query length is more or equal     minimum length then

$query = htmlspecialchars($query); 
// changes characters used in html to their equivalents, for example: < to &gt;

$query = mysql_real_escape_string($query);
// makes sure nobody uses SQL injection

$raw_results = mysql_query("SELECT * FROM characters
    WHERE (`name` LIKE '%".$query."%') OR (`player` LIKE '%".$query."%') OR (`dam` LIKE '%".$query."%') OR (`sire` LIKE '%".$query."%') OR (`status` LIKE '%".$query."%')") or die(mysql_error());

// * means that it selects all fields, you can also write: `id`, `title`, `text`
// articles is the name of our table

// '%$query%' is what we're looking for, % means anything, for example if $query is Hello
// it will match "hello", "Hello man", "gogohello", if you want exact match use `title`='$query'
// or if you want to match just full word so "gogohello" is out use '% $query %' ...OR ... '$query %' ... OR ... '% $query'

if(mysql_num_rows($raw_results) > 0){ // if one or more rows are returned do following

    while($results = mysql_fetch_array($raw_results)){
    // $results = mysql_fetch_array($raw_results) puts data from database into array, while it's valid it does the loop

        echo "Searched term:<br>";
echo "<b>" . $query . "</b>";
echo "<br><br>";
echo "Results:<br>";
foreach($results as $index => $resultArray) {
$resultString = $index+1 . " - ";
foreach($resultArray as $key => $value) {
    if (strpos($value, $query) !== FALSE) { // strpos returns a value between 0 and n if the string is found; if it's NOT found, it returns FALSE - due to PHP's veeeerry loose typing, we need to use !== rather than simply !=, because otherwise 0 will return **as** FALSE
        $resultString .= "<b>" . $value . "</b>";
    } else {
        $resultString .= $value;
    }
    $resultString .= " - ";
}
echo substr($resultString, 0, -3) . "<br>"; // We're chopping off the last " - "
}
    }

}
else{ // if there is no matching rows do following
    echo "No results found.";
}

}
else{ // if query length is less than minimum
echo "Search term is invalid.  Minumum search length is: ".$min_length;
}
?>

预先感谢您的帮助。

在使用以下建议之一之后,我得到了很多这样的错误:警告:/home3/hunstami/public_html/characters/search.php的第63行中为foreach()提供了无效的参数1

我猜我只是试图将其错误地实现到我的代码中,但是就像我上面说的那样,我是一个全新的人。

我的头顶上有两种方法可以做到这一点。 两者都涉及将打算将要写入屏幕的html保留在变量中一会儿。

方法A-在结果集中循环时加粗字符串

// In while loop
row = "#".$results['id']." - ";

if $results['name'] == $query {
 row = row."<strong>".$query."</strong>";
else {
 row = row.$query;
}

row = row." - ".$results['breed']." - ".$results['gender'] // SNIP, use the rest like you use it now

方法B-返回字符串并查找并替换搜索词

html = "";

// while loop
  html = html."#".$results['id']." - ".$results['name']." - ".$results['breed']." - ".$results['gender']." - ".$results['sire']." x ".$results['dam']." - ".$results['genetics']." - ".$results['body']." Base - ".$results['mane']." Mane - ".$results['tail']." Tail - ".$results['eye']." Eyes - ".$results['markings']." - Born: ".$results['birthdate']." - ".$results['bodytype']." Body Type - ".$results['traits']." - ".$results['defects']." - ".$results['extras']." - Achievements: ".$results['achievements']." - Status: ".$results['status']." - Notes: ".$results['notes']." - Played by ".$results['player']."<br><br>";

// end while

html = str_replace(html, $query, "<strong>".$query."</strong>");

echo html;

我相信您正在寻找这样的东西:

echo "Searched term:<br>";
echo "<b>" . $query . "</b>";
echo "<br><br>";
echo "Results:<br>";
foreach($results as $index => $resultArray) {
    $resultString = $index+1 . " - ";
    foreach($resultArray as $key => $value) {
        if (strpos($value, $query) !== FALSE) { // strpos returns a value between 0 and n if the string is found; if it's NOT found, it returns FALSE - due to PHP's veeeerry loose typing, we need to use !== rather than simply !=, because otherwise 0 will return **as** FALSE
            $resultString .= "<b>" . $value . "</b>";
        } else {
            $resultString .= $value;
        }
        $resultString .= " - ";
    }
    echo substr($resultString, 0, -3) . "<br>"; // We're chopping off the last " - "
}

我不知道是否可以在问题的答案中包含这种类型的内容,但我还建议您用PDO替换您的查询(实际上很简单,但比简单的mysql_query()更安全类型的函数-使您更容易受到SQL注入攻击的影响-这样的内容:

好吧,我建议的第一件事是将您的数据库调用转换为PDO。 在Google上快速搜索“ PHP PDO教程”之类的内容将为您找到指南,但是最终它并没有比简单的mysql_query()更复杂-而是更安全。

在这种情况下,我将执行以下操作:

try {
    $db = new PDO('mysql:host=YOUR HOST; dbname=YOUR DATABASE', 'YOUR USERNAME', 'YOUR PASSWORD');
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}

try {
    $stmt = $db->prepare("SELECT * FROM CHARACTERS WHERE (name LIKE :query) OR (player LIKE :query) OR (dam LIKE :query) OR (sire LIKE :query) OR (status LIKE :query);")
    $stmt->execute([
        "query" => "%" . $query . "%"; // This binds ":query" to the value that you give it. It takes an array.
    ]);
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}

我认为它也更干净。 :)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM