2017-07-24 44 views
0

好的,我对PHP很陌生,并且构建了一个问题/回答站点。我想要一个页面,用户可以在其中搜索问题表以找到问题,经过一些研究和工作后,我已经提出了这个问题,但我的问题是常见的话。如果用户在搜索中输入“is”,每个问题都会显示“is”。我的问题是1)我的这种搜索功能的方法是完全错误的吗?或2)是否有一种方法,我可以注入一个常用单词的数组,以便从查询中省略?从php/mysql搜索程序中删除常见词

search_reslut.php:

<?php 


$servername = "127.0.0.1"; 
$username = "dylan326"; 
$password = ""; 
$dbname = "questions87"; 
$port = 3306; 

// Create connection 
$conn = new mysqli($servername, $username, $password, $dbname, $port); 
// Check connection 
if ($conn->connect_error) { 
    die("Connection failed: " . $conn->connect_error); 
} 

echo "Your search results: <br>"; 
echo "<br />"; 
$query = $_POST['query']; 

$query = "$query $query $query"; 
$pieces = explode(" ", $query); 
$qindex0 = $pieces[0]; // piece1 
$qindex1 = $pieces[1]; // piece2 
$qindex2 = $pieces[2]; // piece3 
$qindex3 = $pieces[3]; 
$qindex4 = $pieces[4]; 
$qindex5 = $pieces[5]; 
$qindex6 = $pieces[6]; 



echo $query; 

$sql = "select q_id, question, username, q_date from questions where (question like '%$qindex0%' or question like '%$qindex1%' or question like '%$qindex2%' or question like '%$qindex3%' 
or question like '%$qindex4%' or question like '%$qindex5%' or question like '%$qindex6%')"; 



$result = $conn->query($sql); 

if (mysqli_num_rows($result) > 0) { 
    // output data of each row 
    while($row = mysqli_fetch_array($result)){ 

     $question = $row['question']; 

echo ('<a href="totalqs.php?q_id=' . $row['q_id'] .'" >' . $question .'Asked by:'.' '.$row['username'].' '.$row['q_date'] .' </a>' . '<br>'); 


}} 

else {echo "No resluts found";} 




?> 
+2

这个脚本有相当多的问题。但我无论如何无聊,所以我会为你重写整个事情。可能需要一段时间。 – icecub

+0

你想了解的东西叫做“停词”。他们是不属于重要词汇的单词。 https://en.wikipedia.org/wiki/Stop_words这些通常保存在一个对象或数组中,用于过滤文档中所有单词集合中的单词。 –

+0

我很认真。已经在研究它。评论里面的代码解释一切:) – icecub

回答

1

MySQL不得不做关键词搜索方便,比你在做什么更快的能力。这是通过MATCH(column) AGAINST ('words to search')语法完成的。将FULLTEXT索引添加到您的表格中,查找要进行搜索的列(question)。然后,像这样的工作,去返回的搜索词

// Get the query. escape all single quotes. 
$words = str_replace("'","\'",$_POST['query']); 

$sql = <<< "SQL" 
select q_id, question, username, q_date from questions 
where MATCH(`question`) AGAINST('$words' IN BOOLEAN MODE) 
SQL; 

$result = $conn->query($sql); 

的好处约FULLTEXT搜索的是,他们会自动排除在搜索你的常用词(停用词)至少一个所有问题。了解更多here以及here

如果你有停用词自定义列表,你可以从$words字符串删除它们执行查询

$stopWords = [ 
    '/is/', 
    '/the/' 
]; 

// Where is the cat >> Where cat 
$words = preg_replace($stopWords,'',$words); 

from the docs前:

Full-text indexes can be used only with MyISAM tables. (In MySQL 5.6 and up, they can also be used with InnoDB tables.) Full-text indexes can be created only for CHAR, VARCHAR, or TEXT columns.

+0

是的,我看到一些关于匹配aghost的东西,我会努力工作,看看我能否得到它的工作。 – do734

+0

我收到这个错误“当我尝试插入这个错误时,警告:mysqli_num_rows()期望参数1为mysqli_result,布尔在/ home/subuntu/workspace/question_practice/search_result.php中给出的第56行”。 if语句需要修改? – do734

+0

这是第56行:if(mysqli_num_rows($ result)> 0) – do734