it is not a great idea to put quotes around everything going into an sql statement, but luckily DBI has methods built in to help you quote intelligently. Check the docs for $dbh->quote() and $dbh->quote_identifier. great tips for using these methods can be found in chromatic's DBI is OK. I find I often use this bit of code from the article ('cause hash slices are so cool):
my $table = 'uregisternew';
my @fields = qw( country firstname lastname userid password address1 c
+ity state province zippostal email phone favorites remaddr gender inc
+ome dob occupation age );
my $fields = join(', ', @fields);
my $values = join(', ', map { $dbh->quote($_) } @formdata{@fields});
$sql = "INSERT into $table ($fields) values ($values)";
$sth = $dbh->prepare($sql);
$sth->execute();
$sth->finish();
the one change I sometimes have to make is to the line my $fields = join(', ', @fields);. If you're using a DB that allows spaces in column names, you'll need to quote the column names using code like my $fields = join(', ', map {dbh->quote_identifier($_) }@fields);.
The take home message is, when in doubt use $dbh->quote() on any value you specify in your query, and use $dbh->quote_identifier() on any column or table name. Also, the docs recommend using the quote-like qq{} around sql statements containing variables prepared in this way, so that nothing gets misquoted. rewriting chromatic's example a little, I get a piece of code that looks like this:
my $table_name = $dbh->quote_identifier(uregisternew);
my @fields = qw( country firstname lastname userid password address1 c
+ity state province zippostal email phone favorites remaddr gender inc
+ome dob occupation age );
my $fields = join(', ', map { $dbh->quote_identifier($_) } @fields);
my $values = join(', ', map { $dbh->quote($_) } @formdata{@fields});
$sql = qq{INSERT into $table_name ($fields) values ($values)};
$sth = $dbh->prepare($sql);
$sth->execute();
$sth->finish();
hth,
--au
-
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.