Updated date:

How to search for multiple keywords and long text in MySql Table using PHP?

Timothy is an enthusiast programmer and loves developing websites. He is expert in HTML, CSS, JavaScript, PHP, C#, and ASP[dot]NET.

What this article will cover?

In this tutorial I’ll illustrate how to implement the multiple keyword search technique. The focus is on searching one or more keywords or even full sentence or long text specified by a user in search text box. The text by user will be searched in specified field of the MySql Table and the result containing all rows that match one or more keywords will be displayed.

how-to-search-for-multiple-keywords-and-long-text-in-mysql-table-using-php

1. Setup MySql Table

To implement this tutorial you require a MySql Table. In this example I have created a very simple Table named 'table1' with only one Field named 'field1'.

CREATE TABLE IF NOT EXISTS `table1` (
  `field1` varchar(500) NOT NULL
) ;

After creating a table, insert some data into it. If you don’t know how to insert data in database table follow the link:

2. Create HTML Form

The next step is to create HTML form. The HTML Form, in this tutorial, is very simple form. It has a label, a text box (also called INPUT box), and a search button. This form allows user to type one or more keywords in the text box and search those values by clicking search button. The form will look like following:

HTML Search Form

HTML Search Form

The HTML form has two attributes namely 'action' and 'method'. In the 'action' attribute I have specified the name of the page, which is this page itself (i.e. search.php), to which the data from the form is submitted. Also note the name attribute of the text box. This name will be used to extract values of text box in PHP code.

<form action="search.php" method="post" >
	<h3>Search Keywords:</h3>
	<input type="text" name="keyword">
	<input type="submit" value="Search">
</form>

3. Connect to MySql

The following code is for connecting to MySql server.

You need to modify the code according to your server's setting.

 <?php

   $db_host="localhost";
   $db_user="root";
   $db_pass="";
   $db_name="Search_DB";

    $db = new mysqli($db_host, $db_user, $db_pass, $db_name);
    
    if($db->connect_error){
       die("Connection failed: " . $db->connect_error);
    }

?>

4. Build the Logic

This is the next step after creating user interface (UI) and specifying connection setting to MySql. The logic which I have implemented is given in code below:

 <?php

if(!empty($_POST))
{
      $aKeyword = explode(" ", $_POST['keyword']);
      $query ="SELECT * FROM table1 WHERE field1 like '%" . $aKeyword[0] . "%'";
     
     for($i = 1; $i < count($aKeyword); $i++) {
		if(!empty($aKeyword[$i])) {
			$query .= " OR field1 like '%" . $aKeyword[$i] . "%'";
		}
      }
    
     $result = $db->query($query);
     echo "<br>You have searched for keywords: " . $_POST['keyword'];
					
     if(mysqli_num_rows($result) > 0) {
		$row_count=0;
		echo "<br>Result Found: ";
		echo "<br><table border='1'>";
		While($row = $result->fetch_assoc()) {   
			$row_count++;						  
			echo "<tr><td> ROW ".$row_count." </td><td>". $row['field1'] . "</td></tr>";
		}
		echo "</table>";
    }
    else {
		echo "<br>Result Found: NONE";
    }
}

?>

The logic is fairly simple. First I have checked if the form is submitted to make sure the code will only execute when user click search button:

if(!empty($_POST))

after this I have extracted the values from HTML text box, separated each words from string using explode() function and stored as array in variable $aKeyword

$aKeyword = explode(" ", $_POST['keyword']);

In next lines I have generated query that will search the keywords in 'field1' of 'table1'. For this I have looped through the values in array $aKeyword and added each keyword to the SELECT query to be searched in the field1 and executed the query.

$query ="SELECT * FROM table1 WHERE field1 like '%" . $aKeyword[0] . "%'";
   for($i = 1; $i < count($aKeyword); $i++) {
	if(!empty($aKeyword[$i])) {
		$query .= " OR field1 like '%" . $aKeyword[$i] . "%'";
	}
   }
$result = $db->query($query);

5. Display the Result

The result is displayed as HTML table in which the first column shows the serial number for rows and second column displays the data fetched from the matching rows in the 'field1'.

The following image shows the searching with keywords ‘bengal’ and ‘nicobar’

Search for keywords ‘‘bengal’ and ‘nicobar’

Search for keywords ‘‘bengal’ and ‘nicobar’

and the result shows the rows containing those keywords. In the following image I have underlined the words which are found in the row.

Result for keywords ‘‘bengal’ and ‘nicobar’

Result for keywords ‘‘bengal’ and ‘nicobar’

similarly another search shows the result found for keywords ‘seventh’, ‘second’, and ‘Thailand’

Search for keywords ‘seventh’, ‘second’, and ‘Thailand’

Search for keywords ‘seventh’, ‘second’, and ‘Thailand’

Result for keywords ‘seventh’, ‘second’, and ‘Thailand’

Result for keywords ‘seventh’, ‘second’, and ‘Thailand’

6. Conclusion

This search facility is very handy in case of following:

  • To search more than one value in database field.
  • To search long sentence in the database.
  • To implement auto suggestion text box.
  • To find duplicate value in database such as 'Book Title', 'Title of Research Paper' and any other long text.

Comments

Timothy Malche (author) from Jabalpur, M.P., India on July 08, 2020:

yes you can easily perform this with a little change in the code from this article.

Himani Prajapati on July 08, 2020:

I have made HTML page where there are 10 text box

and I want every time users fills a textbox, it adds to SQL statement and shows the final.

If a user wants to search data only on parameter or on 5 parameter ,its shows what he wants !!

Sam on February 10, 2020:

Thank you so much for your great works.

Is it possible to show only for exact searched words?

e.g: search for Able only showing 'You are Able to do it' not showing all texts which includes Able word. e.g Acceptable, accountable, adorable, warrantable and more...

Jhon on February 10, 2020:

It's very useful for me...

but i want search multiple word in multiple line in the form.

please help me how change it.

Thanks

David on February 04, 2020:

thanks for this article, it was really hrlpful.

Timothy Malche (author) from Jabalpur, M.P., India on January 27, 2020:

can you explain the problem?

saber on January 25, 2020:

it is not working with me

zanoth on October 15, 2019:

it will be useful thx.

Dimuthu on September 27, 2019:

Thanks, it's very helpful for me...

Raphael Banda on July 25, 2019:

This is great. I am also working on something that can ride on your great idea. Mine is to search for particular words in the sentence and compare with what is in the database and give it a score depending on the database where such a word is coming from.

John on June 12, 2019:

Superb!...One quick question, how do you display only the matched key words in the "found " column?

Saleem on April 26, 2019:

Usefull

Saju on April 01, 2019:

Thanks

TJ on March 07, 2019:

This code is very well done. However, can it work for multiple words in quotes. Such as searching for "These Words"? Would it try to search for "These & Words"? I assume I would need more logic but not sure how to implement that. Any thoughts are appreciated and thanks for sharing this solution!

Alessio on January 11, 2019:

Hi, I love this solution and it works wonders... my only issue is displaying results in order (based on word matches). With the code above, it will display them in database order.

So I looked all over the internet and it looks hards to implement... usort functions arrays and stuff like that.

Could you help out?

Thanks again

Timothy Malche (author) from Jabalpur, M.P., India on December 15, 2018:

Thanks

cacious on December 14, 2018:

Awesome and simplest code seen for far.

DM on August 16, 2018:

will this work with prepared statements?

Related Articles