This code gets very hard to follow because you keep jumping back and forth between generating HTML and building and executing an SQL query. Try to do one thing at a time and progress to the next thing that needs to be done. It will make your code much easier to follow and debug.
Your program looks fine until the foreach loop. You are asking for a row of data to be returned as an array of values but you assign the result to a single scalar. As a result, you'll only get one value back for each call to fetchrow_array. To fix this, either receive the values into an array or use fetchrow_arrayref to get a reference to an array of values.
The other problem is inside the foreach. You need nested loops - one to iterate through the rows and an inner loop to iterate through the values in the row.
The second half of your program should look something like this.
my $i; # output column headers foreach $i(@field_desc) { print "<TH>$i</TH>\n"; } print qq `</TR>`; my $sth = $dbh->prepare($SQL); $sth->execute() or die $dbh->errstr; my $row; foreach $row ( $sth->fetchrow_arrayref )# while more rows fetch next o +ne { print "<TR>"; foreach my $cell (@$row) { print "<td>$cell</td>"; } print "</TR>"; } print "</TABLE>"; print $q->end_html; $dbh->disconnect() or die $dbh->errstr;
You might also consider using CGI methods to generate your html. The foreach loop could be reduced to this.
foreach $row ($sth->fetchrow_arrayref) { print Tr(td($row)); }
--- print map { my ($m)=1<<hex($_)&11?' ':''; $m.=substr('AHJPacehklnorstu',hex($_),1) } split //,'2fde0abe76c36c914586c';
In reply to Re: foreach loop
by pfaut
in thread foreach loop
by r_mehmed
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |