Just a hint: it looks as though you're working without warnings or strict. While their restrictions cause extra work, they will catch many typos and will prevent you from leaking variables across scopes you thought were independent - both of which can cause very subtle bugs that can be almost impossible to track down. Do yourself a favour, get in the habit of using my generously and make it second nature to start every script with
#!/usr/bin/perl -w use strict;

(Or, if you're using a reasonably recent version of Perl, use warnings; rather than the -w.)

In your case f.ex, the following code:
my $sth = $dbh->prepare ("SELECT id, body FROM news"); $sth->execute (); while (my ($news_id, $news_body) = $sth->fetchrow_array()) { my $sth = $dbh->prepare ("SELECT COUNT(id) FROM comments WHERE id += $news_id"); $sth->execute (); # was this missing from your snippet accidentall +y? my ($comments) = $sth->fetchrow_array(); print "$news_id, $news_body, $comments"; }
while rather not recommendable as a casual reader might confuse the inner and outer $sth with one another, would at least have worked.

Makeshifts last the longest.


In reply to Re: Looping with DBI by Aristotle
in thread [untitled node, ID 178308] by Samn

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.