Losing has asked for the wisdom of the Perl Monks concerning the following question:
sub insert_row{ if( $#_ < 2 ){ print 'USAGE: $rv = insert_row($DB_TYPE, $DB_HANDLE, $TABLE, $COL1 +, $COL2, $VAL2, $VAL2)'; return 0; } my $db_type = shift; my $dbh = shift; my $table = shift; if( ($#_+1) % 2 != 0 ){ print "COLUMN/VALUE mismatch @ insert_row($db_type,$dbh,$table...) +"; return 0; } my $num_cols = ($#_+1)/2; my $val_index = ($#_+1)/2; my $col_index = 0; my %columns = (); my $x = 0; for($x = 0, $x < $num_cols, $x++){ $columns{$_[$col_index]} = $_[$val_index]; $col_index++; $val_index++; } my $sql = "INSERT INTO " . $table . " ("; while ( my ($key, $value) = each(%columns) ) { $sql .= "$key,"; } chop $sql; $sql .=") VALUES ("; for( $x = 0; $x < $num_cols; $x ++ ){ $sql .= '?,'; } chop $sql; $sql .= ')'; my $sth = $dbh->prepare($sql); my @bind_values = (); while ( my ($key, $value) = each(%columns) ) { push @bind_values, $value; } return $sth->execute(@bind_values); }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Insert Row
by Rhandom (Curate) on Dec 07, 2006 at 16:11 UTC | |
by Rhandom (Curate) on Dec 07, 2006 at 16:20 UTC | |
by reneeb (Chaplain) on Dec 08, 2006 at 08:07 UTC | |
by Rhandom (Curate) on Dec 10, 2006 at 07:12 UTC | |
|
Re: Insert Row
by talexb (Chancellor) on Dec 08, 2006 at 04:19 UTC |