skx has asked for the wisdom of the Perl Monks concerning the following question:
I appreciate this might be more of an SQL question than a perl one, but I'm hoping I've missed something.
I have a table which looks like this:
CREATE TABLE articles ( id int(11) NOT NULL default '0', title varchar(65) NOT NULL default '', bodytext text NOT NULL, PRIMARY KEY (id) ) TYPE=MyISAM;
Now I wish to allow users to search these objects in a "typical" fashion.
The naive approach I started with, using DBI, was:
my @terms = split( / /, $search_terms ); my $querystr = "select id,title,bodytext from articles where "; my $count = 0; foreach my $term ( @terms ) { if ( $count ) { $querystr .= " or "; } $querystr .= "bodytext like '%$term%' "; $count++; } $querystr .= "order by id desc"; # Do the execution my $query = $db->prepare( $querystr ); $query->execute();
This builds up a query string like "select ... from articles where text like %a% or text like %b% or text like %c%".
However this is bad code, it doesnt use parameters like most of my DBI code, and it doesnt allow flexiability. I realise I wish the user to be allowed to search:
My SQL-fu is weak, and I see nothing obvious in the DBI docs.
Any assistance is welcome, although I should point out this is just a small part of an application which is working (and designed) pretty well - so I think switching to Class::Dbi is unlikely.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: OT - Searching databases effectively
by Tanktalus (Canon) on Mar 29, 2005 at 05:54 UTC | |
by skx (Parson) on Mar 30, 2005 at 04:54 UTC | |
|
Re: OT - Searching databases effectively
by inman (Curate) on Mar 29, 2005 at 09:19 UTC | |
by skx (Parson) on Mar 30, 2005 at 04:55 UTC | |
|
Re: OT - Searching databases effectively
by astroboy (Chaplain) on Mar 29, 2005 at 09:35 UTC | |
by skx (Parson) on Mar 30, 2005 at 04:55 UTC | |
|
Re: OT - Searching databases effectively
by naChoZ (Curate) on Mar 29, 2005 at 13:46 UTC | |
|
Re: OT - Searching databases effectively
by TedPride (Priest) on Mar 29, 2005 at 17:18 UTC |