braindamage
braindamage

Reputation: 2256

mysql LIKE = imprecise search

I'm using a simple query for my search:

SELECT * FROM table WHERE field LIKE '%term%'

if I have a field = "Company Name 123" and I search for Company 123 the result is null

how can I improve this? it only finds if the term is in sequence

Upvotes: 2

Views: 331

Answers (4)

oezi
oezi

Reputation: 51797

you could:

  • split your searchterm into words and build a query with a lot of ANDs (or ORs if you just want to find one of the parts) out of it (ugly, but i've seen this a lot of times)
  • replace ' '(space) with % (thats a wildcard) in your term (the way to go)

Upvotes: 0

Piotr
Piotr

Reputation: 4963

You need to put a % between Company and 123 in order for it to match. You might want to check out full text search functions.

Upvotes: 1

Vadyus
Vadyus

Reputation: 1329

try to replace spaces
$searchtext =str_replace(' ','%',$searchtext);

Upvotes: 0

jon_darkstar
jon_darkstar

Reputation: 16768

Replace spaces with %

$newTerm = str_replace(' ', '%', $term);
$sql = "SELECT * FROM table WHERE field LIKE '%$term%'"

$r = mysql_qery($sql, $conn);

Upvotes: 2

Related Questions