Skip to content Skip to sidebar Skip to footer

Any-word Search Using LIKE %

I have a database table which has a field firstname and a field lastname. I'm trying to implement an any-word search system using a search box where if let's say that we have a use

Solution 1:

I might have misunderstood but have you considered just doing this:

SELECT * FROM customer WHERE
    CONCAT(firstname, " ", lastname) LIKE '%$pattern%'

if the user enters more than one word, separated by whitespaces, simple split the string into words and modify the query to

SELECT * FROM customer WHERE
    CONCAT(firstname, " ", lastname) LIKE '%$word1%'
 OR CONCAT(firstname, " ", lastname) LIKE '%$word2%'
 OR CONCAT(firstname, " ", lastname) LIKE '%$word3%'
 ...

Solution 2:

Hope this helps

$whereclauses=array();

$terms = explode(' ', $search_term);
foreach ($terms as $term) {
    $term = mysql_real_escape_string($term);
    $whereclauses[] = "CONCAT(first_name, ' ', last_name) LIKE '%$term%'";
}
$sql = "select * from table where";
$sql .= implode(' and ', $whereclauses);

Post a Comment for "Any-word Search Using LIKE %"