In my web application I am planning to include a Search field which will allow users to enter a string.
This string will then be used to compare against rows of data in multiple tables for example in this database. (this is just an example, in the real problem there is about 20 tables).
Table List:
- Customer
- Books
- Paintings
What is the best way to do a search, as this is my first time doing one that would look over multiple tables?
Do you just go through the tables sequentially comparing each row to the search string or can you make a query that searches the whole database in general?
Should you stop the search once you found a exact match or do you just continue the search regardless if you found a match? Incase there are multiple rows of the same type?
I would like to do this in the most “correct” way possible I had a look at some examples but they only seem to relate to one or two table searches.
I have this pseudo code in my head for what I might do so if you could give me feedback on that too
Get string from $_POST['search']
Strip string of special characters that could be used for Mysql injection.
Connect to db
Search first table for row that is LIKE string
If match found then add to result object
Search next table, and repeat.
When finished search disconnect from DB.
So I hope you lot will be able to guide me link to materials so I can implement this piece of functionality as best as possible.
Thankyou 🙂
First of all, let you know that this will become in an very poor performance search if search condition is ‘contains’ but not
starts with. Also that indexes are needed for all searchables columns.Whell, the most easy way to do this query is to make a big view with an union of all search fields:
Then perform query over view:
Notice that this don’t solve your requeriment to get results only from first table where string appears, you can stop php fetching rows when priority change is found.