tags:

views:

66

answers:

4

Basically i want to add wildcards to the the col value when searching...

Usually I do this the other way around like this:

WHERE cakes.cake_name LIKE '%$cake_search%'

however now i want it to match the inverse:

the user searches for 'treacle sponge', i want this to match a row where the cake_name column = 'sponge'.

is this possible?

+3  A: 
WHERE '$cake_search' LIKE  concat('%',cakes.cake_name, '%')

should work. It will need a full table scan but so will the inverse query. Have you looked into full text search for MySQL? It will likely make this sort of query more efficient.

Martin Smith
hmmm this doesnt seem to be working, will try EXPLAINing it...
Haroldo
@Haroldo. What is the datatype of your column? If fixed length char you might need to trim spaces before appending the wildcards. `concat('%',trim(cakes.cake_name), '%')`
Martin Smith
Hi Martin, its a VARCHAR 20 whos contents will always be trimmed but could contain a space in the interior ie 'bakewell tart'. Uffo's solution worked fine for me, but ill just try your ammended one tyo satisfy curiousity!
Haroldo
@Martin yep, this works too! Which is best though?!!!
Haroldo
@Haroldo - Definitely Full Text Search if that's an option for you. My answer is pretty inefficient as it needs to scan every record.
Martin Smith
A: 

You would have to split the user supplied input on the space character and dynamically construct your query to check the column for those values:

$input = "treacle sponge";
$input_words = explode(' ', $input);

$sql_where = "WHERE cakes.cake_name IN('" . implode("','", $input_words) . "')"; // generates: WHERE cakes.cake_name IN('treacle','sponge')
Dennis Haarbrink
+2  A: 

Why not using MATCH?

MATCH(`cake_name`) AGAINST ('treacle sponge')
Uffo
This requires a FULLTEXT index, which is only available in MyISAM, and not, for example, InnoDB.
Zurahn
this works great for me, (I'm using MyISAM), thanks Uffo
Haroldo
Don't forget to mark the answer as ACCEPTED, if that solves you're problem
Uffo
A: 

In order to prevent SQL-Injection, I suggest using prepared statements.

$prepStmt = $conn->prepare('SELECT ... WHERE cakes.cake_name LIKE :cake_search
');
if($prepStmt->execute(array('cake_search'=>"%$cake_search%"))) {
 ...
}

Or, using full text search:

$prepStmt = $conn->prepare('SELECT ... WHERE MATCH (`cake_name`) AGAINST (:cake_search IN BOOLEAN MODE)');
if($prepStmt->execute(array('cake_search'=>$cake_search_words))) {
 ...
}

See http://stackoverflow.com/questions/3238855/json-specialchars-json-php-5-2-13 for a complete example.. ;)

Javaguru
thanks - i plan to upgarde to PDO soon so this will come in handy
Haroldo