【发布时间】:2014-02-21 17:48:00
【问题描述】:
几年前我一直在使用这个小模板
// get the q parameter from URL
$q = $_REQUEST["q"];
$hint = "";
session_start();
require ('connect.php');
$get_qst = mysql_query("SELECT question FROM questions WHERE question LIKE '%$q%'") or die(mysql_error());
if (mysql_num_rows($get_qst) >= 1) {
while ($qst = mysql_fetch_array($get_qst)) {
$a[] = $qst['question'];
}
}
else {
$a[] = "";
}
// Fill up array with names
// lookup all hints from array if $q is different from ""
if ($q !== "") {
$q = strtolower($q);
$len = strlen($q);
foreach ($a as $name) {
if (stristr($q, substr($name, 0, $len))) {
if ($hint === "") {
$hint = $name;
}
else {
$hint .= "<br /> $name";
}
}
}
}
// Output "no suggestion" if no hint were found
// or output the correct values
echo $hint === "" ? 'No questions found, <a href="javascript:void(0);" id="btn_askqst" onclick="$(\'#qst\').val($(\'#search_qst\').val());">ask question?</a>' : $hint;
代码所做的是将输入字段与数据库中的行进行比较。问题是,例如 ff 我的数据库中有一个问题说“你更喜欢 PHP 还是 ASP?”有人搜索“PHP 还是 ASP?”它会说没有问题。原因是它不检查单个单词,它只检查句子的开头。所以为了让我看到这一点,我需要按正确的顺序写下每个单词,尽管我不需要写出整个问题。
如何检测该单词是否在问题中?
我很抱歉解释不好。英语不是我的母语,我真的不知道如何解释。
【问题讨论】:
-
Please, don't use
mysql_*functions in new code。它们不再维护and are officially deprecated。看到pink box?改为了解prepared statements,并使用PDO 或MySQLi - this article 将帮助您决定哪个。如果你选择 PDO,here is a good tutorial.