Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

With the below code I'm trying to display the numeric count of all q1 answers that are "upright". It's not erroring out, it's printing the hash value. I just don't know how I can get the value of the count back. Can someone help?
my $data = qq[SELECT COUNT(*) FROM questions WHERE `q1` = "upright"]; my $sth = $dbh->prepare($data); $sth->execute() or die $sth->errstr; print $sth;

Replies are listed 'Best First'.
Re: Getting a count of all rows in MySQL
by graff (Chancellor) on Nov 30, 2008 at 23:23 UTC
    Take a longer look at the DBI manual. You want one of these additional things after you do the "execute" call:
    while ( my @row = $sth->fetchrow_array ) { print "@row\n" } # or while ( my $row_ref = $sth->fetchrow_arrayref ) { print "@$row\n" } # or my $allrows_ref = $sth->fetchall_arrayref; for my $row ( @$allrows_ref ) { print "@$row\n"; }
    There are other useful methods for fetching the results of queries, all nicely documented in the manual.
      my $data = qq[SELECT COUNT(*) FROM questions WHERE `q1` = "upright"]; my @results = $dbh->selectrow_array($data); print $results[1];
      you can use this.
Re: Getting a count of all rows in MySQL
by Anonymous Monk on Nov 30, 2008 at 23:22 UTC
    my $data = qq[SELECT COUNT(*) FROM questions WHERE `q1` = "handheld"]; my $sth = $dbh->prepare($data); $sth->execute() or die $sth->errstr; my $results = $sth->fetchrow_array(); print $results;
    Cheers!
Re: Getting a count of all rows in MySQL
by brsaravan (Scribe) on Dec 01, 2008 at 07:03 UTC
    The selectcol_arrayref() also will help you for getting the count.
    my $data = qq[SELECT COUNT(*) FROM questions WHERE `q1` = "upright"]; my $count = $db_handle->selectcol_arrayref($data); print "Count $count->[0]\n";
    Note: $db_handle is the database handle used in your code.