Except, of course, that interpolating user-supplied input directly into your SQL statements is
bad ju-ju. Much better would be:
my @where;
my @values;
my $sql = 'select * from table';
if defined $var1 { push @where, 'column1 = ?'; push @values, $var1; }
if defined $var2 { push @where, 'column2 = ?'; push @values, $var2; }
if defined $var3 { push @where, 'column3 = ?'; push @values, $var3; }
$sql = $sql . ' where ' . join(' and ', @where);
my $sth = $dbh->prepare_cached($sql);
$sth->execute(@values);
or
my @values = (undef, $var1, $var2, $var3);
my @where;
my $sql = 'select * from table';
my @defined_values;
foreach my idx (1..3) {
if defined $values[$idx] {
push @where, qq(column$dx = ?);
push @defined_values, $values[$idx];
}
}
$sql = $sql . ' where ' . join(' and ', @where);
my $sth = $dbh->prepare_cached($sql);
$sth->execute(@defined_values);
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.