0

I have a search engine type website. It takes the users input, stores the query as $q, explodes the query and searches the database. It then displays the results with the name and web address of each result.

For example, if i searched for "computer programming"... Stack Overflow, stackoverflow.com would be my result. However, it displays twice. (once for computer, and once for programming.)

I tried to solve this with the array_unique function, and it does not work.

any help would be appreciated.

    // trim whitespace

$trimmed = trim($q);
// seperate key-phrases
$trimmed_array = explode(" ", $trimmed);

// remove duplicates

$clean_array = array_unique($trimmed_array);

//query dataabase
foreach ($clean_array as $trimm){
     $query = mysql_query("SELECT * FROM forumlist WHERE `keys` LIKE '%" . mysql_real_escape_string($trimm) . "%' ORDER BY rating DESC, total_ratings DESC") or die(mysql_error());

Thank you!

1
  • u need to run array_unique on the results from db Commented May 3, 2011 at 5:22

1 Answer 1

2
//query dataabase
$query = 'SELECT * FROM forumlist  ';
$where = array();
foreach ($clean_array as $trimm){
     $where[] = " `keys` LIKE '%" . mysql_real_escape_string($trimm) . "%' ";
}

if(!empty($where)){
    $query .= " WHERE ". implode(' OR ', $where);
}
$query .= " ORDER BY rating DESC, total_ratings DESC";
$result = mysql_query($query) or die(mysql_error());
Sign up to request clarification or add additional context in comments.

9 Comments

That works. It gets rid of the duplicate results. However I now get this error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE keys LIKE '%computer%' OR keys LIKE '%programming%' ORDER BY ratin' at line 1. Thanks for your help
please show me the whole query. by using echo $query, before mysql_query()
It is something with the second search term. I tried the query as "computer programming" and this is the echo statement: SELECT * FROM forumlist WHERE keys LIKE '%computer%' ORDER BY rating DESC, total_ratings DESC. The correct links that should return from "computer" do return, however the links from "programming" do not.
is it complete query after using "computer programming"
It seems that it runs through the query and display process for "computer" and then shows the error I printed above. For example, "computer" has 2 unique results. "programming" has 2 unique results. "computer programming" returns the 2 results for "computer" and then an error message. "lollipop computer" returns 0 results and the error message.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.