I want to search my database, for example for the word "google yahoo", and when I enter that I should able to look the rows which has google and yahoo. It is not required to be in the same order and google besides yahoo. No matter wherever it is in the line and give me a simple logic to it. I canto query that thing, something like select * from table where column like("%google%yahoo%")
. I want to develop this thing in PHP, but how can I insert %. Do I need to use if
statement so that I can insert % in between the words whenever I find spaces, or is there any other logic to make it simpler?
If you want to check, if a string contains another string, you can use stristr
. This could look like the following
// for fixed strings
if ( stristr($text, 'google') !== FALSE && stristr($text, 'yahoo') !== FALSE)
// both found
// for dynamic amount of strings
$searchfor = array('google','yahoo');
foreach ($searchfor as $needle) {
if (stristr($text, $needle) === FALSE) {
// $needle not found
} else {
// $needle found
}
}
Another possibility to do this would be with preg_match
. You should first be sure, what exactly is it you want to do and then decide which method you want to use.
So from what I understand, you want rows where the value of a certain column is either google or yahoo (or whatever words are provided)
SELECT * FROM tablename WHERE columnname LIKE "%google%" AND columnname LIKE "%yahoo%"
(replace the AND
with OR
if you are ok with either of them)
Essentially your PHP code should split the given input on the spaces, thus obtaining an array of the words.
Next, when you build the query, for each word it should append the following clause:
columnname LIKE "%word%"
(you may want to filter out common words from your search eg a, in, of, etc)