in reply to dbi insert

This question has been more than answered, but i wanted to point out that this code could be much more maintainable if you stored the names of your CGI param variables (which, if you notice, are most conveniently the same as your database field names) in an array:
my @fields = qw(fornavn efternavn cpr adresse zip city tjenestested); my $cgi = new CGI; # apply validation/error checking as needed # in this case, if no param is found, undef is default my @params = map { $cgi->param($_) || undef } @fields; # connect to database . . . my $sth = $dbh->prepare( 'INSERT into people(' . join(',', @fields), ') values(' . join(',', map { '?' } @fields), ')' ) or die $dbh->errstr; $sth->execute(@params) or die $dbh->errstr;
It looks a bit intimidating, but you only need to worry about changing ONE line (the first one in this example) if you add or subtract fields. Read up on map and join for more info. :)

jeffa

Replies are listed 'Best First'.
Re: (jeffa) Re: dbi insert
by Anonymous Monk on Oct 17, 2001 at 12:37 UTC
    I have tried most of what has been suggested, but I still cannot get it to work.
    It sends back NO error code, but it does not insert any data in my db

    ******************code*********************

    #!/usr/local/bin/perl -wT

    use strict;
    use CGI;
    use DBI;

    my $cgi = new CGI;
    my $fornavn = $cgi->param("fornavn");
    my $efternavn = $cgi->param("efternavn");
    my $cpr = $cgi->param("cpr");
    my $adresse = $cgi->param("adresse");
    my $zip = $cgi->param("zip");
    my $city = $cgi->param("city");
    my $tjenestested = $cgi->param("tjenestested");


    my $dbh = DBI->connect("DBI:mysql:um","root","") ||
    die "Could not connect: $DBI::errstr\n";

    my $sth = $dbh->prepare("INSERT into people (fornavn,
    efternavn, cpr, adresse, zip, city, tjenestested)
    values ($fornavn, $efternavn, $cpr, $adresse, $zip,
    $city, $tjenestested)");

    $sth->execute();
    $sth->finish();


    $dbh->disconnect;

    print "Content-type: text/html\n\n";
    print "<HTML>";
    print "<HEAD>";
    print '<META HTTP-EQUIV="Refresh" CONTENT="1; URL=um.htm">';
    print "</HEAD>";
    print '<BODY bgcolor="#333366">';
    print "</BODY>";
    print "</HTML>";

    ******************code*********************
      Try changing the connect call to:
      my $dbh=DBI->connect('DBI:mysql:um', 'root', '', {AutoCommit=>1, RaiseError=>1});
      The RaiseError value means that any subsequent DBI error will cause your program to die with an error message. AutoCommit explicitly controls whether you require a commit call. mysql used not to support transactions, so committing was irrelevant. I don't know if this is still true.