Solved

Multiple keywords %LIKE% match myslq query problem

Posted on 2009-05-02
7
443 Views
Last Modified: 2013-12-12
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
Comment
Question by:derek2277
7 Comments
 
LVL 4

Expert Comment

by:Fugas
ID: 24289054
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
 
LVL 19

Expert Comment

by:NerdsOfTech
ID: 24289182
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
 

Author Comment

by:derek2277
ID: 24292248
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
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 19

Expert Comment

by:NerdsOfTech
ID: 24292754
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
 
LVL 19

Expert Comment

by:NerdsOfTech
ID: 24292760
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
 
LVL 23

Assisted Solution

by:Tiggerito
Tiggerito earned 50 total points
ID: 24293399
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
 
LVL 19

Accepted Solution

by:
NerdsOfTech earned 200 total points
ID: 24293598
I concur -- as relevancy, in this case, is highly important.
0

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

Phishing is at the top of most security top 10 efforts you should be pursuing in 2016 and beyond. If you don't have phishing incorporated into your Security Awareness Program yet, now is the time. Phishers, and the scams they use, are only going to …
This article discusses how to create an extensible mechanism for linked drop downs.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

706 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now