Mysql – Searching for a keyword across multiple columns

MySQLmysqliPHP

I have a set of names of schools stored in each row in my schools table. the same table has four different category columns which store the names of the subjects they offer. I want to enable functionality where the user conducts a search on the table to find out all the names of the schools which teach a particular subject (for eg: physics). The name of the particular subject could be stored in any of the four subject columns. Please suggest a mysqli_/mysql_ query to conduct such a search or if you may so please, suggest a PHP script that would achieve the above functionality.

Best Answer

You could write a simple query using OR in WHERE clause and passing your search string.

SELECT school_name
FROM schools
WHERE Subject1 = 'Physics'
OR Subject2 = 'Physics'
OR Subject3 = 'Physics'
OR Subject4 = 'Physics'

You can parameterize the search string and pass on to this query.