How to Search a MySQL Table for Any Word or Phrase Using PHP


In this tutorial, we will show how you can search a MysQL Table for any word or phrase which you are looking for.

Say, if you are searching a database of various fruits and you want to see if they carry mangoes, so you look for the keyword 'Mango'. How can we create a PHP query to a MySQL table to only send back results of rows having the word 'Mango' in it.

This can be useful for many different types of applications. As an example, let's take Amazon is a huge online retailer that sells thousands and thousands of different products. They have all of these products stored in a database. On amazon's home page is a search bar where a user can type in the item he or she is looking for. If the user searches for the term 'ipad', Amazon searches through all the items in its database and returns the products which contain the name 'ipad' in it. It then retrieves those items and displays them to the user.

So many other sites follow this format, including practically all retailers, so that customers can find the products they are looking for. Therefore, it has great application.


So how is this done with PHP and a MySQL database?

The general format of code to do this is:


As an example to demonstrate this, below is a table of list of fruits:



Below is the complete code to create the table above:

In this above code, we're going to alter the 3rd block of code, which has the comments "ATTENTION." This is the block of code which will allow us to search the table for whatever word or phrase we are looking for.

How to Search a MySQL Table For a Certain Word or Phrase Using PHP

Now we're going to alter the 3rd block of code above to search for the word, 'Mango'.

Below is the line of code which searches for the keyword 'Mango' from the MySQL database table.

This produces the following table, which is shown below.


And you can do this with any phrase which you put in between the statement '%phrase to search for%'.

HTML Comment Box is loading comments...