pc0019 has asked for the wisdom of the Perl Monks concerning the following question:

## get a list of the field names my $keys = join (', ', @keys); ## get number of placeholders required (number of field names) my $placeholder_count = @data; ## make $placeholder_count number of ?'s with a comma after each my $placeholders = '?, ' x $placeholder_count; ## remove last space and comma $placeholders = substr($placeholders, 0, - 2); ## make a string containing each piece of data separated by commas my $data = '"' . join('", "', @data) . '"'; my $dbh = DBI->connect("DBI:mysql:database=$database;host=localhost", +$username, $password, {'RaiseError' => 1}); my $sth = $dbh->prepare("INSERT INTO $table ($keys) VALUES ($placehold +ers)") or die $dbh->errstr; $sth->execute($data) or die $dbh->errstr;

I am making a script which sends data to a MySQL database. From the code above, the penultimate line would read something like this:

my $sth = $dbh->prepare( "INSERT INTO table01 (field1, field2, field3) VALUES (?, ?, ?)" ) or die $dbh->errstr;

And on the last line, $data = '"rise", "against", "ftw"'. The problem is, I get the message:

DBD::mysql::st execute failed: called with 1 bind variables when 3 are needed

Perl is seeing my $data at $sth->execute($data) as one variable, not a list. So how could I create the variables there?

I guess there are other ways to do this, but I would like to know how to create variables within Perl with specific names anyway - getting a language to write its own code is awesome :D

Replies are listed 'Best First'.
Re: Creating strings with specified names
by kyle (Abbot) on Aug 05, 2008 at 21:51 UTC
    $sth->execute(@data) or die $dbh->errstr;

    You don't have to put quotes around the elements of @data when you use placeholders—DBI does that for you.

      Oops, should have thought of that. Thanks!

      Is what I suggested possible?

        Writing Perl that creates variables with a name specified at run time is pretty easy, but it's generally not a good idea.

        $name = 'foo'; $$name = 'bar'; print "foo = $foo\n"; __END__ foo = bar

        Note that doesn't work if you use strict (which is always a good idea). In that case, you wind up with something like this:

        my $name = 'foo'; { no strict 'refs'; $$name = 'bar'; } print "foo = $main::foo\n";

        See how I still had to use the explicit package name to refer to the variable for printing.

        You can do a lot with eval too.

Re: Creating strings with specified names
by chromatic (Archbishop) on Aug 05, 2008 at 23:34 UTC
    Perl is seeing my $data at $sth->execute($data) as one variable, not a list.

    That's because $data is a scalar, not a list. join creates a string from a list.