2

I've got the code below that works but I need to know how to bind them for security. If I just replace $new_row with ? and put it in execute I get an error. Thanks for your help.

foreach my $field (@account_field_order) {
$new_row .= "'" . param($field) . "', ";
}#foreach
$new_row .= "'$status'";
my $dsn = "DBI:mysql:$database";
my $dbh = DBI->connect($dsn, $MYSQLuserid, $MYSQLpassword ) 
          or die $DBI::errstr;
my $sth = $dbh->prepare(qq(INSERT INTO $table VALUES ($new_row) )) or die $DBI::errstr;
$sth->execute() or die $DBI::errstr;
2
  • You need one question mark ? for each field. Commented Mar 5, 2012 at 16:13
  • See TLP's answer on placeholders. Another reason to use placeholders: you can run prepared statements that only need to be parsed and compiled once by the DB manager. Commented Mar 5, 2012 at 19:25

2 Answers 2

5

You will want to use placeholders, and never interpolate variables in strings. You should probably use taint mode and de-taint your param values before using them, if safety is important to you. Documentation on placeholders here.

Try something like:

my @values = map param($_), @account_field_order; # add values to array
push @values, $status;                  # for simplicity
$new_row = join ", ", ("?") x @values;  # add ? for each value

... # basically same code as before, except the execute statement:

$sth->execute(@values);      # arguments given will be inserted at placeholders
Sign up to request clarification or add additional context in comments.

3 Comments

ok.. I used your code and I get this error.. Column count doesn't match value count at row 1 at account.cgi line 745.
my @values = map param($_), @account_field_order; push @values, $status; my $new_row = join ", ", ("?") x @values; my $dsn = "DBI:mysql:$database"; my $dbh = DBI->connect($dsn, $MYSQLuserid, $MYSQLpassword ) or die $DBI::errstr; my $sth = $dbh->prepare(qq(INSERT INTO $table VALUES ($new_row) )) or die $DBI::errstr; $sth->execute(@values) or die $DBI::errstr;
@ta Well, the best I can do is repeat what the error says to you. You have a sync error somewhere. Try and find it. Oh, by the way, you are using use strict; use warnings;, right? If not, I suggest you do.
0

If your values were in a hash, there's the insert_hash example in the docs (under prepare_cached). Adjust as appropriate if not using an array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.