搜索结果中的粗体搜索字词

时间:2016-01-03 05:22:35

标签: php mysql search

当用户搜索我的数据库时,我希望搜索词在结果中加粗。我似乎无法找到可以轻松实现到现有代码中的教程或解释。我是一个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;
}
?>

提前感谢您的帮助。

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

我猜我只是试图在我的代码中错误地实现这一点,但就像我上面所说的那样,我对此非常陌生。

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分:0)

我相信你正在寻找类似的东西:

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。快速谷歌搜索类似&#34; PHP PDO教程&#34;会找到你的指南,但最终它并不比简单的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();
}

我认为,它还有点清洁。 :)