0

I have a PHP search script that searches a MySQL database to answer questions. Currently my database is set out like this...

id
question = what is the time
answer = The time is 12:00

This data is then sent to my PHP code:

<?php

mysql_connect("localhost","username","password");
mysql_select_db("database");

if(!empty($_GET['q'])){
$query=mysql_real_escape_string(trim($_GET['q']));
$searchSQL="SELECT * FROM questions WHERE `question` LIKE '%{$query}%'  LIMIT 1";
$searchResult=mysql_query($searchSQL);

while($row=mysql_fetch_assoc($searchResult)){
$results="{$row['answer']}";
}

echo $results;
}

?>

Currently, the users query must contain exactly the same text as the question field. My question is; how can I make this work so it triggers a certain for several keywords?

I hope you can understand my question

2
  • Could you give an example of the sort of keywords you'd like to match a particular question with? Commented Oct 11, 2011 at 19:06
  • I think that kind of natural language processing is going to be beyond the scope of a SO Q&A. Commented Oct 11, 2011 at 19:07

2 Answers 2

1

I think full test search index can help http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html SOUNDEX function can be useful in this context too. You can split query to keywords and generate dynamic SQL but it is inefficient (performance issues SQL injection attacks ) see http://php.net/manual/en/function.split.php

Alternative is to add table QUESTION_KEYWORD(QUESTION_ID,KEYWORD), split question and search this table to find best QUESTION_ID, but full text search index is more efficient. In fact full text search index uses similar data structure to optimize test search.

Sign up to request clarification or add additional context in comments.

Comments

0

For an easy quick-fix based on your comment you could do something as simple as this:

// Assuming query string is ?q=make,sponge,cake
$searchSQL="SELECT * FROM questions WHERE ";
$count = 0;
foreach (explode(',', $_GET['q']) as $query) {
  $searchSQL .= "`question` LIKE '%" .mysql_real_escape_string(trim($query)) . "%' ";
  if ($count++ > 0) {
    $searchSQL .= ' OR ';
  }
}

$searchSQL .= ' LIMIT 1';
$searchResult = mysql_query($searchSQL);

1 Comment

You could just reverse the process, ie q=how,to,make,a,sponge,cake, if it's ok to be loose with your matching (using OR) then that would work. If you want a selective AND then I'm afraid it's more like natural language processing as stated above

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.