in reply to Re^2: Building SQL Query on the fly
in thread Building SQL Query on the fly
So just do chop $SQL; or $SQL =~ s/,$//; to get rid of the comma, before you add the next part of the statement ($SQL .= " FROM ...").
But I think the sample code you just gave is a bit off track. Let's go back to your CGI param string (from the OP):
If you get your params like this:../cgi-bin/script.pl?column3=1&column2=2&column1=3
Then you can form the string of column names like this:my $q = new CGI; my $href = $q->Vars;
I don't think you'll ever need to worry about any extra commas with that approach, but if you want to be totally certain:my $col_string = join( ',', sort {$$href{$a} <=> $$href{$b}} keys %$hr +ef );
Or, using something more like your approach, just append column names in order, and get rid of the last comma:$col_string =~ s/^,+//; # remove leading commas $col_string =~ s/,+$//; # remove trailing commas $col_string =~ s/,{2,}/,/g; # reduce adjacent commas to ","
Either way, now you just finish the SQL statement:my $col_string = ''; for my $var ( sort {$$href{$a} <=> $$href{$b}} keys %$href ) { $col_string .= "$var,"; } chop $col_string; # remove final comma
Also, in all cases, if/when you decide (or realize) that you do need to worry about security issues, make sure to test the "$href" keys (assumed table column names) against a known (untainted) list that is based directly on the how the table was defined. Delete any hash keys from the CGI parameter string that do not exactly match a known table column.my $sql = "SELECT $col_string FROM my_table";
This sort of dynamic query construction is an area where things can go horribly wrong if you are not meticulously careful about checking your tainted input. If you don't have "-T" on the shebang line of your script (to turn on taint-checking), add it now.
This is what I am doing with the XML::Generator, but the stuff it returns is hard coded, and not dynamic variables...
That's why I say you should use XML::Simple (or something else besides XML::Generator) -- you need to write XML data based on a data structure, where the highest (outermost) level of the structure is a hash.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: Building SQL Query on the fly (join is your friend)
by grinder (Bishop) on Oct 08, 2007 at 10:16 UTC | |
|
Re^4: Building SQL Query on the fly
by hallikpapa (Scribe) on Oct 08, 2007 at 05:22 UTC | |
by graff (Chancellor) on Oct 08, 2007 at 05:35 UTC | |
by hallikpapa (Scribe) on Oct 08, 2007 at 06:28 UTC |