• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 456
  • Last Modified:

Multiple keywords %LIKE% match myslq query problem

I am trying to get the script below to output the query results like this:

the dark knight batman
the batman joker
the batman gotham
the batman
superman vs batman
superman batman

However when I run this script the output results are as so:

the dark knight batman
the dark knight batman
the batman joker
the batman joker
the batman gotham
the batman gotham
the batman
the batman
superman vs batman
superman vs batman
superman batman
superman batman

Can anyone point me into the right direction on how to remove the duplicate result?

Thanks!
<?php
$hostname_logon = "localhost" ;   
$database_logon = "dbname" ;  
$username_logon = "username" ;  
$password_logon = "password" ;   
//open database connection
 $connections = mysql_connect($hostname_logon, $username_logon, $password_logon) or die ( "Unabale to connect to the database" );
 //select database
 mysql_select_db($database_logon) or die ( "Unable to select database!" );
 
//specify how many results to display per page
$limit = 10;
 
// Get the search variable from URL
  $var = "batman forever" ;
//trim whitespace from the stored variable
  $trimmed = trim($var); 
//separate key-phrases into keywords
  $trimmed_array = explode(" ",$trimmed);
 
// check for an empty string and display a message.
if ($trimmed == "") {
  $resultmsg =  "<p>Search Error</p><p>Please enter a search...</p>" ;
  }
 
// check for a search parameter
if (!isset($var)){
  $resultmsg =  "<p>Search Error</p><p>We don't seem to have a search parameter! </p>" ;
  }
// Build SQL Query for each keyword entered
foreach ($trimmed_array as $trimm){
     
// EDIT HERE and specify your table and field names for the SQL query
     $query = "SELECT * FROM popular_searches2 WHERE query LIKE \"%$trimm%\" ORDER BY query DESC" ; 
     // Execute the query to  get number of rows that contain search kewords
     $numresults=mysql_query ($query);
     $row_num_links_main =mysql_num_rows ($numresults);
 
      // now let's get results.
      $query .= " LIMIT $limit" ;
      $numresults = mysql_query ($query) or die ( "Couldn't execute query" );
      $row= mysql_fetch_array ($numresults);
 
      //store record id of every item that contains the keyword in the array we need to do this to avoid display of duplicate search result.
      do{
 //EDIT HERE and specify your field name that is primary key
          $adid_array[] = $row[ 'query' ];
      }while( $row= mysql_fetch_array($numresults));
 } //end foreach
 
if($row_num_links_main == 0 && $row_set_num == 0){
   $resultmsg = "<p>Search results for:" . $trimmed  ."</p><p>Sorry, your search returned zero results</p>" ;
}
   //delete duplicate record id's from the array. To do this we will use array_unique function
   $tmparr = array_unique($adid_array);
   $i=0;
   foreach ($tmparr as $v) {
       $newarr[$i] = $v; 
       $i++;
   }
 
// display what the person searched for.
 if( isset ($resultmsg)){
  echo $resultmsg;
  exit();
 }else{
  echo "Search results for: " . $var;
 }
 
foreach($newarr as $value){
 
// EDIT HERE and specify your table and field names for the SQL query
 $query_value = "SELECT * FROM popular_searches2 WHERE query = '$value'";
 $num_value=mysql_query ($query_value);
 $row_linkcat= mysql_fetch_array ($num_value);
 $row_num_links= mysql_num_rows ($num_value);
 
//now let's make the keywods bold. To do that we will use preg_replace function.
//EDIT parts of the lines below that have fields names like $row_linkcat[ 'field1' ]
//This script assumes you are searching only 3 fields. If you are searching more fileds make sure that add appropriate line. 
  $titlehigh =  $row_linkcat[ 'query' ];
 
foreach($trimmed_array as $trimm){
    if($trimm != 'b' ){
//IF you added more fields to search make sure to add them below as well.
        $titlehigh = preg_replace( "'($trimm)'si" ,  "<b>\\1</b>" , $titlehigh);
     }
//end highlight
 
?>
<?php echo $titlehigh; ?><br>
 
<?php
}   //end foreach $trimmed_array 
 
}  //end foreach $newarr
?>

Open in new window

0
derek2277
Asked:
derek2277
2 Solutions
 
FugasCommented:
Hi,

you should use only one query with condition build from the string array WHERE query LIKE "%$trimmed[0]%" OR query LIKE "%$trimmed[1]%" OR query LIKE "%$trimmed[2]%"
0
 
NerdsOfTechTechnology ScientistCommented:
Try this:
<?php
$hostname_logon = "localhost" ;   
$database_logon = "dbname" ;  
$username_logon = "username" ;  
$password_logon = "password" ;   
//open database connection
 $connections = mysql_connect($hostname_logon, $username_logon, $password_logon) or die ( "Unabale to connect to the database" );
 //select database
 mysql_select_db($database_logon) or die ( "Unable to select database!" );
 
//specify how many results to display per page
$limit = 10;
 
// Get the search variable from URL
  $var = "batman forever" ;
//trim whitespace from the stored variable
  $trimmed = trim($var); 
//separate key-phrases into keywords
  $trimmed_array = explode(" ",$trimmed);
 
// check for an empty string and display a message.
if ($trimmed == "") {
  $resultmsg =  "<p>Search Error</p><p>Please enter a search...</p>" ;
  }
 
// check for a search parameter
if (!isset($var)){
  $resultmsg =  "<p>Search Error</p><p>We don't seem to have a search parameter! </p>" ;
  }
// Build SQL Query for each keyword entered
foreach ($trimmed_array as $trimm){
     
// EDIT HERE and specify your table and field names for the SQL query
     $query = "SELECT * FROM popular_searches2 WHERE query LIKE \"%$trimm%\" ORDER BY query DESC" ; 
     // Execute the query to  get number of rows that contain search kewords
     $numresults=mysql_query ($query);
     $row_num_links_main =mysql_num_rows ($numresults);
 
      // now let's get results.
      $query .= " LIMIT $limit" ;
      $numresults = mysql_query ($query) or die ( "Couldn't execute query" );
      $row= mysql_fetch_array ($numresults);
 
      //store record id of every item that contains the keyword in the array we need to do this to avoid display of duplicate search result.
      do{
      //EDIT HERE and specify your field name that is primary key
          $adid_array[] = $row[ 'query' ];
      }while( $row= mysql_fetch_array($numresults));
 } //end foreach
 
if($row_num_links_main == 0 && $row_set_num == 0){
   $resultmsg = "<p>Search results for:" . $trimmed  ."</p><p>Sorry, your search returned zero results</p>" ;
}
   //delete duplicate record id's from the array. To do this we will use array_unique function
   $tmparr = array_unique($adid_array);
   $i=0;
   foreach ($tmparr as $v) {
       $newarr[$i] = $v; 
       $i++;
   }
 
// display what the person searched for.
 if( isset ($resultmsg)){
  echo $resultmsg;
  exit();
 }else{
  echo "Search results for: " . $var;
 }
 
foreach($newarr as $value){
 
// EDIT HERE and specify your table and field names for the SQL query
 $query_value = "SELECT * FROM popular_searches2 WHERE query = '$value'";
 $num_value=mysql_query ($query_value);
 $row_linkcat= mysql_fetch_array ($num_value);
 $row_num_links= mysql_num_rows ($num_value);
 
//now let's make the keywods bold. To do that we will use preg_replace function.
//EDIT parts of the lines below that have fields names like $row_linkcat[ 'field1' ]
//This script assumes you are searching only 3 fields. If you are searching more fileds make sure that add appropriate line. 
  $titlehigh =  $row_linkcat[ 'query' ];
 
foreach($trimmed_array as $trimm){
    if($trimm != 'b' ){
//IF you added more fields to search make sure to add them below as well.
        $titlehigh = preg_replace( "'($trimm)'si" ,  "<b>\\1</b>" , $titlehigh);
     }
//end highlight
 
$atitlehigh[] = $titlehigh;
 
}   //end foreach $trimmed_array 
 
}  //end foreach $newarr
 
// get unique values only
$atitlehigh = array_unique($atitlehigh);
foreach ($atitlehigh as $value){
	echo $value . '<br />';
}
?>

Open in new window

0
 
derek2277Author Commented:
I have been playing around with this and I now can get mysql to return results for each keyword.  The only problem is that it seems to run the query each time and then return 10 results for each separate keyword.  Does anyone know how to condense the results?

The output for the keywords "batman forever" returns 20 results instead of 10:

batman default
batman
batman defaults
batman logo
pink batman
batman the dark knight
batman dark knight
batman friendster
batman begins
batman the dark knight the dark knight
always and forever
forever 21
forever
forever the sickest kids
forever love
flashy diamonds are forever
love forever
forever and always
forever yours
plain yellow background stars forever

Anyone know how to have this return 10 results from the output only?

Thanks,
// Get the search variable from URL
  $var = "batman forever" ;
//trim whitespace from the stored variable
  $trimmed = trim($var); 
//separate key-phrases into keywords
  $trimmed_array = explode(" ",$trimmed);
 
// check for an empty string and display a message.
if ($trimmed == "") {
  $resultmsg =  "<p>Search Error</p><p>Please enter a search...</p>" ;
  }
 
// check for a search parameter
if (!isset($var)){
  $resultmsg =  "<p>Search Error</p><p>We don't seem to have a search parameter! </p>" ;
  }
// Build SQL Query for each keyword entered
foreach ($trimmed_array as $trimm){
 
	$result = mysql_query("SELECT * FROM popular_searches2 WHERE query LIKE '%$trimm%' ORDER BY count DESC LIMIT 10") or die(mysql_error());  
	
	while($row = mysql_fetch_array($result)){
		echo $row['query'];
		echo "<br />";
	}
}
?>

Open in new window

0
Improve Your Query Performance Tuning

In this FREE six-day email course, you'll learn from Janis Griffin, Database Performance Evangelist. She'll teach 12 steps that you can use to optimize your queries as much as possible and see measurable results in your work. Get started today!

 
NerdsOfTechTechnology ScientistCommented:
Since you are LOOPING the query (in this case you are running two querys) you will get a maximum of 20. Instead if you use one execution (with or statements) you can limit the result quantity by 10.

// Get the search variable from URL
  $var = "batman forever" ;
//trim whitespace from the stored variable
  $trimmed = trim($var); 
//separate key-phrases into keywords
  $trimmed_array = explode(" ",$trimmed);
 
// check for an empty string and display a message.
if ($trimmed == "") {
  $resultmsg =  "<p>Search Error</p><p>Please enter a search...</p>" ;
  }
 
// check for a search parameter
if (!isset($var)){
  $resultmsg =  "<p>Search Error</p><p>We don't seem to have a search parameter! </p>" ;
  }
 
// Build ONE SQL Query for keyword(s) entered
 
$i=0
foreach ($trimmed_array as $trimm){
 if ($i==0){
  $conditions = " query LIKE '%";
 else {
  $conditions = " OR query LIKE '%";
 }
 $conditions .= "$trimm%' ";
 $i++;
}
 
$result = mysql_query("SELECT * FROM popular_searches2 
WHERE $conditions 
ORDER BY count DESC LIMIT 10") or die(mysql_error());  
        
while($row = mysql_fetch_array($result)){
 echo $row['query'];
 echo "<br />";
)

Open in new window

0
 
NerdsOfTechTechnology ScientistCommented:
Fixed error. Use this instead :)
// Get the search variable from URL
  $var = "batman forever" ;
//trim whitespace from the stored variable
  $trimmed = trim($var); 
//separate key-phrases into keywords
  $trimmed_array = explode(" ",$trimmed);
 
// check for an empty string and display a message.
if ($trimmed == "") {
  $resultmsg =  "<p>Search Error</p><p>Please enter a search...</p>" ;
  }
 
// check for a search parameter
if (!isset($var)){
  $resultmsg =  "<p>Search Error</p><p>We don't seem to have a search parameter! </p>" ;
  }
 
// Build ONE SQL Query for keyword(s) entered
 
$i=0
foreach ($trimmed_array as $trimm){
 if ($i==0){
  $conditions = " query LIKE '%";
 } else {
  $conditions = " OR query LIKE '%";
 }
 $conditions .= "$trimm%' ";
 $i++;
}
 
$result = mysql_query("SELECT * FROM popular_searches2 
WHERE $conditions 
ORDER BY count DESC LIMIT 10") or die(mysql_error());  
        
while($row = mysql_fetch_array($result)){
 echo $row['query'];
 echo "<br />";
)

Open in new window

0
 
Tony McCreathTechnical SEO ConsultantCommented:
You may find the MySQL full text searches more suitable to what you want. You don't need to split up your words, the search is indexed so a lot faster and it can return results ordered by relevance.

http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html
0
 
NerdsOfTechTechnology ScientistCommented:
I concur -- as relevancy, in this case, is highly important.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Protect Your Employees from Wi-Fi Threats

As Wi-Fi growth and popularity continues to climb, not everyone understands the risks that come with connecting to public Wi-Fi or even offering Wi-Fi to employees, visitors and guests. Download the resource kit to make sure your safe wherever business takes you!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now