tags:

views:

36

answers:

3

Hello.

This may sound easy, but I've been trying - in vain, apparently - to figure out how I can make a query with MySQL that checks if the value (string $haystack ;) ) in a certain column contains certain data ( $needle ;) ), like this:

mysql_query("
SELECT *
FROM `table`
WHERE `column`.contains('{$needle}')
");

In PHP, the function is called substr($haystack, $needle), so maybe:

WHERE substr(`column`, '{$needle}')=1

Thanks in advance!

+2  A: 
WHERE `column` LIKE '%$needle%'

:)

oedo
+2  A: 

Quite simple actually:

mysql_query("
SELECT *
FROM `table`
WHERE `column` LIKE '%{$needle}%'
");

The % is a wildcard for any character. Do note that this can get slow on very large datasets so if your database grows you'll need to use fulltext indices.

WoLpH
+2  A: 

Use:

SELECT *
  FROM `table`
 WHERE INSTR(`column`, '{$needle}') > 0

Reference:

OMG Ponies
surely LIKE is faster than INSTR?
oedo
@oedo: Depends. `LIKE %...%` won't use an index if one is present, so they should be equivalent; `LIKE ...%` would use an index if present. If performance is a real concern, Full Text Search (FTS) would be a better approach.
OMG Ponies
shouldn't it be >=1 or > 0?
arik-so
@arik-so: You are correct, corrected.
OMG Ponies
perfect. just what I've been looking for.
arik-so