chchrist
chchrist

Reputation: 19842

How to search in database when the search term is a string that includes spaces?

I have this string "Beautiful sunset" (notice the double space)

When I search in the database:

SELECT * FROM images WHERE title LIKE '%$string%'

and I search for "Beautiful sunset" (notice the single space) it won't return any results.

How can I tackle this?

Upvotes: 0

Views: 1085

Answers (5)

Muthu Krishnan
Muthu Krishnan

Reputation: 1658

Try this

SELECT * FROM images WHERE where MATCH(title) AGAINST ('$string' IN BOOLEAN MODE)

Check this Link also

http://dev.mysql.com/doc/refman/5.5/en/fulltext-boolean.html

Upvotes: 1

Pinpickle
Pinpickle

Reputation: 1024

If you don't know what string you're going to get (if it isn't "Beautiful sunset" all the time), you could explode the string and make a query based on that. Like so...

$c = false;
$stringtosearch = "Beautiful sunset";
$query = "SELECT * FROM images WHERE";
foreach(explode(" ", $stringtosearch) as $b)
{
   if ($c)
   {
     $query .= " or";
   }
   $query .= " title LIKE " . $b;
   $c = true;
}

And afterwards you would get the variable $query with your query string.

Upvotes: 0

Nagaraju Badaeni
Nagaraju Badaeni

Reputation: 900

split the string by space. now you have two strings something like $str1, $str2 trim this two strings(i.e remove leading and trailing whitespaces) then rebuild string $string = $str1+'%'+$str2

Upvotes: 1

Alexio
Alexio

Reputation: 77

One way you can do this is to use string replace to replace spaces with a wildcard character:

    $string = str_replace(" ", "%", $string);
    $Query  = "SELECT * FROM images WHERE title LIKE '%$string%'";

Upvotes: 0

Grrbrr404
Grrbrr404

Reputation: 1805

You could split your search string into multiple parts using the space and then build a sql like this for every part you have splitted:

SELECT * FROM images WHERE title LIKE '%$part[0]%' 
or title LIKE '%$part[1]%'
or title LIKE '%$part[2]%'
or title LIKE '%$part[3]%'
...

Make sure to skip double spaces / empty parts.

Upvotes: 0

Related Questions