has asked for the wisdom of the Perl Monks concerning the following question:
Hey
Sorry, a newbie type of question, but somehow I never gotten this to work when I tried. Basically I want to retrieve all values from a MySQL database and print it out in a table. The below coding works and displays all the values I want it to display. However, It uses fetchrow_hash, which retrieves the first row values of the table and then calls a while statement using a fetchrow_array, which retrieves all the values except the first row. How can I make this code so it gives it a bit more efficiency by not having to call both fetchrow_hash and array? Isn't there a way just to do something like a while (%hash = $sth->fetchrow_array) to retrieve all the values at once? I tried this but the my script died on me and seemed to slow my server down dramatically? ahh~ I just have a feeling that this is such a simple newbie mistake that I'm doing wrong. It seems like the fetchrow-hash is retrieves ALL the mysql db results (including column names that are not listed in my SELECT statement?) and therefore theirs room for improving efficiency.
print <
ID |
Name |
Company |
Country |
File |
Summary |
Date Submitted |
EOF
#retrieve business plans
$ci_blah = "mypassword";
use DBI;
$dbh_m = DBI->connect('DBI:mysql:companies','myusername',$ci_bla
+h) or die "Couldn't connect to database: " . DBI->errstr;
$sql_m = "SELECT id,firstname,lastname,country,file_name,summ
+ary,date FROM companies_db";
$sth_m = $dbh_m->prepare($sql_m) or die "preparing: ",$dbh_m-
+>errstr;
$sth_m->execute or die "executing: ", $dbh_m->errstr;
$results = $sth_m->fetchrow_hashref;
print " ";
print " $results->{'id'} | ";
print " $results->{'firstname'} $results{'lastname'} | ";
print " $results->{'company'} | ";
print " $results->{'country'} | ";
print " $results->{'file_name'} | ";
print " $results->{'summary'} | ";
print " $results->{'date'} | ";
print " ";
while (@data =
$sth_m->fetchrow_array()) # keep fetching until
# there's nothing left
{
print " ";
print " $data[0] | ";
print " $data[1] $data[2] | ";
print " $data[3] | ";
print " $data[4] | ";
print " $data[5] | ";
print " $data[6] | ";
print " $data[7] | ";
print " ";
}
$sth_m->finish;
$dbh_m->disconnect;
print " ";
my $sth = $dbh->prepare(q{ INSERT INTO sales (product_code, qty, price) VALUES (?, ?, ?) }) or die $dbh->errstr; while (<>) { chomp; my ($product_code, $qty, $price) = split /,/; $sth->execute($product_code, $qty, $price) or die $dbh->errstr; }
|