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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.