Search code examples
mysqlperlsplitsql-like

Perl MySQL - How do I split a search string and match with LIKE %$word1%$word2% "dynamically"?


I am stuck again.

I have a search string and assigned it to a variable:

my $search =  'foo bar blue widget'
$search =~ s/[\n\r]+|^\s+|\s+$//g; #remove leading and trailing spaces n stuff

I was using

SELECT FROM `sometable` WHERE `coltosearch` LIKE '%$search%'

But, would match only "foo bar blue widget" OR "foo".

I want to match "foo bars" or "foobar" too.

So, I think I would have to do:

 my $search =  'foo bar blue widget';
    $search =~ s/[\n\r]+|^\s+|\s+$//g; #remove leading and trailing spaces n stuff
 my $search1 =  $search;
    $search1 =~ s/^\s+|\s+$|\s*//g; #remove all spaces

   SELECT FROM `sometable` WHERE `coltosearch` LIKE '%$search%' OR LIKE '%$search1%'

Well, that may be fine for "foo bar blue widget" and "foobarbluewidget". (if it worked)

So, I am guessing I will have to loop through $search, and assign variables to each word.

But, I never know how many words I will have in $search.

So, I am stuck. Could I do something like:

my $search =  'foo bar blue widget'; #in from search form. Actually a $var
$search1 =~ s/^\s+|\s+$|\s*//g; #remove all spaces
$search1 = "%$search1%"; # Makes %foobarbluewidget%

## Now make individual words somehow ##
my @searcharry;
my $cnt='0';
my $searchword;
my @searchsplit = $search;
while $searchword (@searchsplit){
push (@searcharry,$searchword[$cnt]);
$cnt++;
}

But how do I get @searcharry into:

$search =~ s/\s/%/gi;
$search =~ s/%%/%/gi; #I think makes %foo%bar%blue%widget%

So I can:

 SELECT FROM `sometable` WHERE `coltosearch` LIKE '$search' OR LIKE '$search1'

I am probably way off base. This is really difficult for me. I just want to match any words in the search string or match if all words are run together.

Sorry for being such a noob. My crude attempt, I believe is an insult to Perl and real coders.

Thanks for any help.


Solution

  • If you have $string = "foo bar blue widget", then you'd do something like:

    my @values = split '\s+', $string;
    my $where = "WHERE $col LIKE ?";
    $where .= " OR LIKE ?" x $#values;
    

    This will create a where clause of WHERE column LIKE ? OR LIKE ? OR LIKE ? OR LIKE ? for your "foo bar blue widget" string.

    Then you use DBI placeholders and bind values so you don't have to worry about SQL injection attacks on your code.