The presence of a use CGI; at the head of your script gives me pause as does using an unfiltered filename in a two-argument open and unfiltered, unescaped strings in your SQL. These are potentially very dangerous if exposed to the outside world, allowing execution of arbitrary code and SQL injection. These are a cracker's dream and an admin's nightmare. This is very nearly the worst you can do without malicious intent.
Security aside, you can accomplish this with an algorithm that is essentially what you had in mind, though I would modify it a bit. Something like (untested):
#!/usr/bin/perl use DBI; use strict; use warnings; # Connect to the database my $dbh = DBI->connect('DBI:mysql:mirnas', 'root', 'bi0u90ee') or die "Couldn't open database: $DBI::errstr; stopped"; my $filename = $ARGV[0]; my $table_name = $ARGV[1]; open(INPUT, '<', $filename) or die "Open failed $filename: $!"; #getting the column names from the text file my $line = <INPUT>; chomp($line); my @fields = split('\t+', $line); # prevent undefs foreach my $field (@fields){ print "$field\n"; } # SQL fragment for creating right number of columns my $column_fragment = <<EOSQL; ? TEXT NOT NULL, EOSQL $column_fragment x= @fields; $column_fragment =~ s/,\s*$/\n/; # Strip trailing comma # Whole CREATE TABLE statement with placeholders my $sql = <<EOSQL; CREATE TABLE ? ( $column_fragment ) EOSQL # Binding and execution my $sth = $dbh->prepare($sql) or die "Prepare failed: $DBI::errstr"; $sth->bind_param(1, $table_name) or die "Bind failed: $DBI::errstr"; for my $i (0 .. $#fields) { $sth->bind_param($i+2, $fields[$i]) or die "Bind failed: $DBI::err +str"; } $sth->execute or die "Execute failed: $DBI::errstr";
Note that I've added success tests to every DBI call, added a test on the open, changed to a three-argument open to reduce exposure, and am using bound parameters in place of direct interpolation to handle character escaping. I'd also recommend editing your original post to scrub that password. See Placeholders and Bind Values in DBI.
In reply to Re: DBI question
by kennethk
in thread DBI question
by gogoglou
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |