z28 has asked for the wisdom of the Perl Monks concerning the following question:

Greetings Monks! I seek your wisdom!

I set up a basic SQL search using perl's DBI module. As I was searching through my databases' name column I noticed that the search would only match if the contents of the cell were exactly the same. Thus I set out to create a "loose" search option. Here's the jist of my error creating code:

my $name = $cgi->param("name"); my $dbh = DBI->connect('DBI:mysql:my_db', 'user', 'pass') or die "Couldn't open database: $DBI::errstr"; my $sth = $dbh->prepare( "select * from my_db where name like ?" ) or +die "DBI prepare: $DBI::errstr"; $sth->execute( %name% ) or die "Couldn't execute statement: $DBI::errs +tr";

If I want to return a 'strict' result with the above code I change the execution line to:

$sth->execute( $name ) or die "Couldn't execute statement: $DBI::errst +r";

and it works fine. As soon as I take the dollar sign off it stops working.



As far as I can tell my code follows what was laid out in the following code, which was posted to a perl users discussion group:

my $sth = $dbh->prepare(" SELECT blah FROM blah WHERE blah LIKE ? "); $sth->execute('%foo%');
-z28

Replies are listed 'Best First'.
Re: Using DBI to create 'loose' search options with LIKE and %
by Kanji (Parson) on Mar 08, 2002 at 11:47 UTC

    You're missing quotes ('' in your foo example, but style is arbritrary here) and the scalar prefix for name (so you're searching for the name specified rather than the word 'name' :)).

    $sth->execute("%$name%")

    ... is probably what you're looking for, although you might want to take precautions to check $name doesn't already start.end with %'s.

    On a related note, check out SQL::AnchoredWildcards (alt.) -- an aide for turning strings with regex-style anchors into their SQL equivalents (ie, '^foo' > 'foo%', 'bar' > '%bar%', 'baz$' > '%baz').

        --k.


Re: Using DBI to create 'loose' search options with LIKE and %
by rdfield (Priest) on Mar 08, 2002 at 11:38 UTC
    You're missing quotes around %name% in $sth->execute, apart from that the code is OK.

    rdfield